[英]how to set headers to application/json in angular2
I am trying to send HTTP post request in Angular2 but not able to set headers to content type application JSON.我正在尝试在 Angular2 中发送 HTTP post 请求,但无法将标头设置为内容类型应用程序 JSON。
My code is:我的代码是:
login(url,postdata)
{
var headers = new Headers({'Content-Type': 'application/json'});
return this._http.post(url,JSON.stringify(postdata),this.headers)
.map(res => res.json())
}
When i checked in network i found that Content-Type is set as text/plain and thus server is not receiving any data.当我检查网络时,我发现 Content-Type 设置为文本/纯文本,因此服务器没有接收任何数据。 Any suggestions will be appreciated.任何建议将不胜感激。
Try this code:试试这个代码:
private _getHeaders():Headers {
let header = new Headers({
'Content-Type': 'application/json'
});
return header;
}
public login(url, postdata){
let options = new RequestOptions({
headers: this._getHeaders()
});
return this.http.post(url, JSON.stringify(postdata),options).map(res => res.json());
}
change _http.post
parameters :更改_http.post
参数:
login(url,postdata) {
var headers = new Headers({'Content-Type': 'application/json'});
return this._http.post(url,postdata,{headers:headers})
.map(res => res.json())
}
Referencing the Angular 2 Angular Http Guide @angular/http has been deprecated, and @angular/common/http should be the one you are using in your Angular 2 App.参考 Angular 2 Angular Http 指南@angular/http 已被弃用,@angular/common/http 应该是您在 Angular 2 应用程序中使用的那个。 Because if you do not specify http headers the default request will be sent as Content-Type text/plain, How you modify the http headers is to:因为如果您不指定 http 标头,默认请求将作为 Content-Type text/plain 发送,修改 http 标头的方法是:
import { HttpClient, HttpHeaders } from '@angular/common/http';
.....
const req = this.http.post('/api/PostRequest/',
JSON.stringify(object),
{
headers:new HttpHeaders()
.set('Content-Type','application/json')
}).subscribe();
You should use code like this你应该使用这样的代码
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let options = new RequestOptions({ headers: headers });
return this.http.post(url, JSON.stringify(postdata), options).map(res => res.json());
Angular 9 version for 2020 2020 年的 Angular 9 版本
export class ApiService {
private headers = new HttpHeaders({
'Content-Type': 'application/json',
});
constructor(
private http: HttpClient) {
}
get(path: string, params: HttpParams = new HttpParams()): Observable<any> {
return this.http.get(`${environment.apiUrl}${path}`, {params, headers: this.headers});
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.