问题
I'm trying to understand this issue i had for days now, so i want to send a post request with username and password using angular 7 to a nodejs rest api for authentication but it sends an empty body here is the login method in authservice.ts:
login(username: string, password: string): Observable<any> {
let httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Accepts': 'application/json'
})
};
return this.http.post<any>(
`${this.HOST_DOMAINE}/bo/api/authenticate`,
{
'username': username,
'password': password
},
httpOptions
);
}
and here is the method for sending it in auth.component.ts:
signin() {
this.loading = true;
this.submitted = true;
if (this.loginForm.invalid) {
this.loading = false;
return;
}
this._authService.login(
this.loginForm.controls.username.value,
this.loginForm.controls.password.value)
.subscribe(
data => {
console.log(data);
if (data['done'])
this._router.navigate([this.returnUrl]);
else {
this.showAlert('alertSignin');
this._alertService.error(data['msg'] + "");
this.loading = false;
}
},
error => {
console.log(error);
this.showAlert('alertSignin');
this._alertService.error(error.message);
this.loading = false;
}
);
}
I was searching for solution but everything i tried doesn't work and i don't know what did i miss here. Note: I'm a beginner
回答1:
For anyone who is facing the same issue here is a temp solution! So i found out that it was a problem of cross origin here is a work around it:
login(username: string, password: string): Observable<any> {
let httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}),
params: new HttpParams()
.set("username", username)
.set("password", password),
withCredentials: true
};
return this.http.post<any>(
`${this.HOST_DOMAINE}/bo/api/authenticate`,
null,
httpOptions
);
}
I set the parameters in http header params with credentials as 'include' and replace content type from json to form-urlencoded in nodejs express middleware i allowed cross origin here is the snippet:
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", req.get('origin'));
res.header('Access-Control-Allow-Credentials', true);
res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
it worked but still it needs test on the origin
来源:https://stackoverflow.com/questions/54552540/angular-7-post-request-always-send-a-null-body