【发布时间】:2016-10-02 10:25:06
【问题描述】:
我正在尝试在服务中使用 Angular 2(2.0.0-rc.1) 执行简单的检查登录方法。当我尝试将内容类型设置为 application/json 时,它在发送到我的 Web api 后端时从不设置标头。
import { Injectable } from '@angular/core';
import { HTTP_PROVIDERS, Http, Response, Headers, RequestOptionsArgs, RequestMethod, Request, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { Other Modules Left out for Security } from 'Hidden';
@Injectable()
export class LoginService {
private _http: Http;
constructor(http: Http) {
this._http = http;
}
CheckLogin(model: CredentialModel) {
let url = 'http://localhost:51671/api/Login';
let data = JSON.stringify(model);
let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json');
let requestOptions = new RequestOptions({
method: RequestMethod.Post,
url: url,
headers: headers,
body: data
});
console.log(requestOptions);
console.log(data);
return this._http.post(url, data, requestOptions);
}
}
来自 Web Api 的请求
OPTIONS /api/Login HTTP/1.1
Host: localhost:51671
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Access-Control-Request-Method: POST
Origin: http://localhost:5616
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2754.0 Safari/537.36
Access-Control-Request-Headers: content-type
Accept: */*
DNT: 1
Referer: http://localhost:5616/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
使用 PostMan 使用完全相同的数据可以正常工作! Angular 2 使用 POST 方法发送 application/json 似乎存在问题。
任何解决此问题的帮助都会有所帮助。愿意尝试任何建议。
【问题讨论】:
-
你可以试试没有 requestOptions 吗?即
return this._http.post(url, data, {headers: headers}); -
这就是我的做法:
this._http.post(url, body, { headers })(哈哈,echonax :D) -
你必须允许CORS请求,check this answer,或者搜索
preflight request,angular2 cors -
我已经尝试了这里的每一步,但仍然遇到同样的错误。对于那些使用它的人,您使用的是最新的 Angular2 RC1 吗?
标签: angular http-headers