我是 angularjs 的新手。我制作了一个简单的应用程序来测试身份验证,方法是通过 post 请求将用户凭据(即用户名和密码)发送到服务器(用 php 编写),但奇怪的是,我无法使用 $_POST 从服务器获取数据,而是可以通过 $_GET 检索它。我已经检查了其他部分以及 CORS 并且没有发现任何错误。如能提供指南,将不胜感激。谢谢。
这是我的角度工厂方法:
app.factory("loginFact", function($http){
this.user = {
isAuthenticated: false,
name: "",
token: ""
}
this.makeLoginRequest = function(user,pass) {
var req = {
method: 'post',
url: 'http://localhost/login/authenticate.php',
headers: {
'Content-Type': "multipart/form-data"
},
params: { username: user, password:pass }
}
$http( req ).success(function(data){
console.log( "Success: " + data )
}).error(function (data) {
console.log( "Error: " + data )
});
}
return{
makeLoginRequest: this.makeLoginRequest
}
});
这是我的服务器部分:
<?php
header('Accept-Charset: utf-8');
header('Connection: keep-alive');
header('Content-Type: multipart/form-data,');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header('Access-Control-Allow-Headers: accept, content-type');
header('Access-Control-Request-Headers: X-Requested-With, accept, content-type');
try{
if(($_POST["username"] == "test") && ($_POST["password"] == "test") ){
echo "{'"id'": '"700'", '"user'": { '"uid'": '"123456'", '"role'": '"admin'", '"name'": '"waqar'" }}";
return;
}else{
echo "phase1: invalid username/password";
return;
}
}catch(Exception $e){
echo $e->getMessage();
}
try{
$request_body = file_get_contents('php://input');
$data = json_decode($request_body);
if($data->username == "test" && $data->password == "test"){
echo "{'"id'": '"700'", '"user'": { '"uid'": '"123456'", '"role'": '"admin'", '"name'": '"waqar'" }}";
return;
}
else{
echo "phase2: Invalid username/password";
return;
}
}catch(Exception $e){
echo $e->getMessage();
return;
}
?>
通过在 params
对象中发送数据,数据将作为查询参数在标头中发送(在 URL - ?key1=value1&key2=value2
中)。
您必须改为使用对象键在正文中发送它们data
:
var req = {
method: 'post',
url: 'http://localhost/login/authenticate.php',
headers: {
'Content-Type': "multipart/form-data"
},
data: { username: user, password:pass }
}
有关更多详细信息,请查看文档。
如果我理解正确,在评论中您问:为什么要将参数放入请求的正文而不是 URL 中?
您可以在URL中发送它们,但会有一些缺点:
- 编码在正文中比在 URL 中更好
- 您可以在正文中发送更多数据,因为URL的长度通常是有限的(因系统而异,但大约2000个字符)
- 欺骗网址更容易
- 系统通常将URL保存在其日志中,因此如果有人看到日志,您可能会暴露客户的帐户(即使您在数据库中加密/散列它们,它们也会以纯文本形式保存)
- 考虑到上一点,在某些国家/地区,记录敏感数据可能是非法的。