当我尝试使用Angular2发布应用程序/json时,我收到一个405错误。我知道这不是CORS问题,因为所有的服务器响应头都已经就绪(Access-Control-Allow- headers,Access-Control-Allow-Methods,Access-Control-Allow-Origin),并且我可以在内容类型为application/x-www-form-urlencoded时执行POST。
尝试使用Angular2发布应用程序/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');
}
}
发布于 2016-04-19 21:08:58
我花了几个小时来寻找这个问题的一致答案。只需在web服务web.config的部分中添加以下内容,就可以为我解决这个问题。
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Headers" value="Content-Type"/>
</customHeaders>
</httpProtocol>
发布于 2016-03-23 22:59:54
我发现这个article清楚地指出CORS请求中不允许使用应用程序/json。Thierry感谢您建议查看jquery请求/响应,因为它让我意识到我是从处理请求的同一服务器上提供html页面的,所以我没有遇到CORS问题。我将添加一个虚拟目录来映射ng2项目,以便可以从为请求提供服务的同一服务器上提供该项目
https://stackoverflow.com/questions/36071536
复制相似问题