![](/img/trans.png)
[英]Can't change Content-Type in http post request using angular
[英]Angular2. Http. Can't send post with body and set Content-Type
我正在编写一个应用程序,使用Angular2作为前端部分(~2.4.0)和ASP.NET CORE作为后端部分。
发送邮件请求时遇到了一个非常大的问题。 Chrome告诉我,我的请求中没有正文,也无法设置内容类型的请求。
我试过几个方面。 但没有人工作
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('authentication', `3123123123`);
let options = new RequestOptions({ headers: headers });
this.http
.post('http://localhost:5000/api/user/login', JSON.stringify(this.loginModel), options)
.subscribe((result) => {
if (result) {
.......
}
});
第二:
PostRequest(url:string,data:any) {
var headers = new Headers();
headers.append("Content-Type", 'application/json');
var requestoptions = new RequestOptions({
method: RequestMethod.Post,
url: url,
headers: headers,
body: JSON.stringify(data)
})
return this.http.request(new Request(requestoptions))
.map((res: Response) =>
res.json()
).subscribe((result) => {
if (result) {
....
}
});
}
第三个:
let headers = new Headers();
headers.append('Accept', 'application/json');
headers.append('Content-Type', 'application/json');
let body = JSON.stringify(loginDto);
let options = new RequestOptions({headers: headers});
return this.http
.post(
'....',
body,
options
)
.map(res => res.json()).subscribe((result) => {
if (result) {
....
}
});
UPD:
我已经尝试了@Akshay Khale方法,它仍然无法正常工作。 我仍然得到带有内容类型的标题
解析度:
问题出在后端。 CORS配置以错误的方式进行。 并且ASP.NET CORE阻止了所有自定义标头。 感谢大家的帮助
在您的代码中,第一个选项应该有效但在第二个参数中您不需要执行JSON.stringify
。
以下是正在运行的代码
它将使用Post请求和控制台转储返回的数据来命中给定的远程URL。
let body:any = { "parameter1": "value1", "parameter2": "value2" };
let url = "example.com";
let response:any;
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
this.http.post(url, body, options).map((res:Response) => res.json()).subscribe(
data => { response = data },
err => console.error(err),
() => { console.log(response) });
乐于帮助 :) :) :)
由于您使用的是Angular 4 RequestOptionsArgs
而不是RequestOptions
,如下所示,
此官方文档处于Experiemental状态
post(url: string, body: any, options?: RequestOptionsArgs) : Observable<Response>
将您的代码修改为,
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('authentication', `3123123123`);
let options : RequestOptionsArgs ={
url: 'http://localhost:5000/api/user/login',
method: RequestMethod.Post,
search : '',
headers : headers,
withCredentials : 'false',
responseType : ResponseContentType.Json
}
this.http
.post('http://localhost:5000/api/user/login',
JSON.parse(this.loginModel), options)
.subscribe((result) => {
if (result) {
.......
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.