Angular 7:发布请求总是发送一个空正文 [英] Angular 7: Post request always send a null body
问题描述
我正在尝试了解这个问题,我已经好几天了,所以我想使用 angular 7 将带有用户名和密码的 post 请求发送到 nodejs rest api 进行身份验证,但它发送了一个空主体,这里是登录方法在 authservice.ts 中:
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
);
}
这里是在 auth.component.ts 中发送它的方法:
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
推荐答案
对于任何面临同样问题的人,这里是一个临时解决方案!所以我发现这是一个交叉起源的问题,这是一个解决方法:
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
);
}
我将 http header params 中的参数设置为include",并将内容类型从 json 替换为 form-urlencoded在 nodejs express 中间件中,我允许跨源这里是片段:
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
这篇关于Angular 7:发布请求总是发送一个空正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!