当我尝试使用Angular2 POST应用程序/ json时收到405错误。我知道它不是CORS问题,因为所有服务器响应头都已到位(Access-Control-Allow-Headers,Access-Control-Allow-Methods,Access-Control-Allow-Origin),我可以在内容类型是application / x-www-form-urlencoded。
使用Angular2尝试POST / json是否存在已知问题?
服务器端代码使用带有IIS服务器的MS Web API以C#编写。
请求信息:
Request URL:http://localhost:9090/api/Authentication/login
Request Method:OPTIONS
Status Code:405 Method Not Allowed
Remote Address:[::1]:9090
Response Headers
view source
Access-Control-Allow-Headers:Content-Type
Access-Control-Allow-Methods:GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin:*
Allow:POST
Cache-Control:no-cache
Content-Length:76
Content-Type:application/json; charset=utf-8
Date:Fri, 18 Mar 2016 14:27:27 GMT
Expires:-1
Pragma:no-cache
Server:Microsoft-IIS/7.5
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET
Request Headers
view source
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:localhost:9090
Origin:http://localhost:3000
Referer:http://localhost:3000/login
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36
代码:
import { Component, View } from 'angular2/core';
import { Router, RouterLink } from 'angular2/router';
import { CORE_DIRECTIVES, FORM_DIRECTIVES } from 'angular2/common';
import { Http, Headers, RequestOptions} from 'angular2/http';
@Component({
selector: 'login'
})
@View({
directives: [RouterLink, CORE_DIRECTIVES, FORM_DIRECTIVES],
templateUrl: 'app/login/login.html',
styles: ['app/login/login.css']
})
export class Login {
constructor(public router: Router, public http: Http) {
}
login(event, username, password) {
event.preventDefault();
let body = JSON.stringify({ userName: "user", password: "pwd", apiKey: "key", role: "role" });
let headers = new Headers({ 'content-type': 'application/json' });
let options = new RequestOptions({ headers: headers });
this.http.post('http://localhost:9090/api/Authentication/login', body, options)
.subscribe(
response => {
localStorage.setItem('jwt', response.json().id_token);
this.router.parent.navigateByUrl('/home');
},
error => {
alert(error.text());
console.log(error.text());
}
);
}
signup(event) {
event.preventDefault();
this.router.parent.navigateByUrl('/signup');
}
}
答案 0 :(得分:1)
我花了几个小时寻找一致的答案。只需将以下内容放在Web服务web.config的部分中,就可以解决这个问题。
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Headers" value="Content-Type"/>
</customHeaders>
</httpProtocol>
答案 1 :(得分:0)
我发现这个article清楚地表明在CORS请求中不允许应用/ json。 Thierry感谢您建议查看jquery请求/响应,因为它让我意识到我正在处理来自处理请求的同一服务器的html页面,所以我没有遇到CORS问题。我将添加一个虚拟目录来映射ng2项目,以便可以从为请求提供服务的同一台服务器上提供它