我需要创建一个登录系统,我尝试将params发送到PHP服务器。
Angular app
return this.http.post<any>('/s/login/index.php', {
username: username,
password: password
}).map(user => {
console.log(username);
// login successful if there's a jwt token in the response
if (user) {
// store user details and jwt token in local storage to keep user logged in between page refreshes
}
return user;
});
}
PHP服务器
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Check if username is empty
if(empty(trim($_POST["username"]))){
$username_err = 'Please enter username.';
$resp->body->message=$username_err;
$resp=json_encode($resp);
echo $resp;
}
但服务器总是返回
{status: "400", body: {message: "Please enter username."}}
答案 0 :(得分:1)
这是因为您没有设置标题。
首先导入必要的模块
import {HttpClient,HttpHeaders} from '@angular/common/http';
import {URLSearchParams} from '@angular/http';
以这种方式试试。
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
let options = {
headers: headers
};
let body = new URLSearchParams();
body.set('username', username);
body.set('password', password);
return this.http.post<any>('/s/login/index.php', body, options).map(user => {
console.log(username);
// login successful if there's a jwt token in the response
if (user) {
// store user details and jwt token in local storage to keep user logged in between page refreshes
}
return user;
});
}
告诉我它是否不起作用。我在这里!