Dav*_*dze 4 c# asp.net-web-api2 angular
邮递员一切都很好。我在服务器上发布了Bearer令牌,并获得了预期的结果。
Angular 2请求:
//app component
test(){
return this.httpService.get('api/user/get', 'application/json')
.subscribe(data=>{
console.log({'loggedIn': true, 'messageText': 'test succeeded'});
},
error=>{
console.log({'loggedIn': false, 'messageText': error});
}
);
}
//http-service
get(url:string, contentType:string):Observable<any> {
let baseUrl:string = "http://localhost:1382/";
let headers = new Headers({
'Accept': 'application/json'
});
//append content-type to headers
headers.append('Content-type', contentType);
//check if localStorage contains token. If yes, append authorization to headers
let token = localStorage.getItem('access_token');
if (token !== '[object Object]' && token !== null) {
headers.append('Authorization', 'Bearer' + ' ' + token);
}
let requestOptions = new RequestOptions({headers: headers});
//send get request
return this.http.get(baseUrl + url, requestOptions)
.map((res:Response)=>res.json())
.catch(this.handleError);
}
Run Code Online (Sandbox Code Playgroud)
它说错误:
OPTIONS http://localhost:1382/api/user/get 405 (Method Not Allowed)
XMLHttpRequest cannot load http://localhost:1382/api/user/get. Response for preflight has invalid HTTP status code 405
<Error>
<Message>Authorization has been denied for this request.</Message>
</Error>
Run Code Online (Sandbox Code Playgroud)
我在Web Api 2 web.config中启用了CORS,如下所示:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type, Authorization, Accept" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
</system.webServer>
Run Code Online (Sandbox Code Playgroud)
有什么建议么?
它在邮递员中工作,因为它是扩展名,它只是发送请求。
另一方面,出于安全原因,从浏览器发送请求时,请求的发送方式有所不同。
首先,浏览器向发送一个OPTIONS请求(所谓的预检请求)http://foo.com/bar。这是为了确定使用这些参数发送请求是否可接受。
您的后端应处理请求,响应并设置响应标头,例如:
Access-Control-Allow-OriginAccess-Control-Allow-HeadersAccess-Control-Allow-CredentialsAccess-Control-Allow-Methods之后,根据OPTIONS响应的标头,浏览器会将IF允许的所有内容(如来源,方法等)发送GET至http://foo.com/bar。
| 归档时间: |
|
| 查看次数: |
6143 次 |
| 最近记录: |