【发布时间】:2016-12-10 12:35:18
【问题描述】:
我有一个简单的代码用于向我的本地服务器发送发布请求。 像这样:
login(event, username, password) {
event.preventDefault();
let body = "grant_type=password&username=" + username + "&password=" + password;
this.http
.post(`${appSettings.API_ENDPOINT_DEV}Login`, body, {headers: contentHeaders})
.subscribe(
response => {
this.accessToken = response.json().access_token;
console.log(this.accessToken);
localStorage.setItem('access_token', this.accessToken);
},
error => {
alert(error.text());
console.log(error.text());
}
);
}
但我在 google chrome 开发控制台中发现了下一个异常。
XMLHttpRequest 无法加载 http://localhost:1216/api/Login。回复 对于预检有无效的 HTTP 状态代码 400
请帮我解决这个问题,因为 Angular 1.x 一切正常。 从谷歌浏览器控制台登录:
Request URL:http://localhost:1216/api/Login
Request Method:OPTIONS
Status Code:400 Bad Request
Remote Address:[::1]:1216
Access-Control-Allow-Origin:*
Cache-Control:no-cache
Content-Length:34
Content-Type:application/json;charset=UTF-8
Date:Thu, 04 Aug 2016 11:43:21 GMT
Expires:-1
Pragma:no-cache
Server:Microsoft-IIS/10.0
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?RDpcU291cmNlc1xHcmFwcHNcVUtfQnJhbmRQcm90ZWN0aW9uXFdlYkFQSVxhcGlcTG9naW4=?=
UPD:
export const contentHeaders = new Headers();
contentHeaders.append('Content-Type', 'application/x-www-form-urlencoded');
contentHeaders.append('Access-Control-Allow-Origin', '*; *');
contentHeaders.append('Access-Control-Allow-Methods', 'POST');
UPD2 从高级 REST 客户端记录
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json;charset=UTF-8
Expires: -1
Server: Microsoft-IIS/10.0
Access-Control-Allow-Origin: *; *
X-Sourcefiles: =?UTF-8?B?RDpcU291cmNlc1xHcmFwcHNcVUtfQnJhbmRQcm90ZWN0aW9uXFdlYkFQSVxhcGlcTG9naW4=?=
X-Powered-By: ASP.NET
Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Date: Thu, 04 Aug 2016 11:59:19 GMT
Content-Length: 316
【问题讨论】:
-
你需要正确配置你的服务器stackoverflow.com/questions/10143093/…
-
使用 Angular 1.x 都可以正常工作。请再次阅读我的问题。
-
contentHeaders是如何定义的? -
Angular 不发送 OPTIONS 请求。此请求由浏览器创建。
-
服务端需要在对 OPTIONS 请求的响应中添加标头。在 Angular 中添加它们是多余的。
标签: typescript angular