I need to create a login system, I try to send the params to the PHP server.
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 server
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;
}
But the server always returns
{status: "400", body: {message: "Please enter username."}}
It is because you are not setting headers.
first import necessary modules
import {HttpClient,HttpHeaders} from '@angular/common/http';
import {URLSearchParams} from '@angular/http';
try it this way.
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;
});
}
Tell me if it does not work. I am here !