[英]CORS issue Angular4 & c# web api
I have a web API that runs on http://localhost:59543/ for which I have enabled the CORS by adding the following to Web.config 我有一个运行在http:// localhost:59543 /上的Web API,已通过将以下内容添加到Web.config中来启用了CORS
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
I have a angular 4 project that run on http://localhost:4200/ . 我有一个在http:// localhost:4200 /上运行的angular 4项目。 I use the following code to make an HTTP request 我使用以下代码进行HTTP请求
LoginService LoginService
@Injectable()
export class LoginService extends BaseService {
request: Http;
constructor(request: Http) {
super(request);
this.request = request;
}
postLogin(body: Object): Observable<any> {
var options = this.options;
options.method = "POST";
return this.request.post(AppSettings.apiURL + "api/Login", body, options)
.map(this.extractData)
.catch(this.handleError);
}
}
Base Service 基础服务
@Injectable()
export class BaseService {
headers: Headers;
options: RequestOptions;
constructor(private http: Http) {
this.headers = new Headers();
let token: string = localStorage.getItem("TOKEN");
if (token != undefined)
this.headers.append("AUTH_TOKEN", token);
this.options = new RequestOptions({ headers: this.headers });
}
public extractData(res: Response) {
let body = res.json();
return body || {};
}
public handleError(error: Response | any) {
return Observable.throw(error.message || error);
}
}
Issue 问题
When I set the header for HTTP request 当我为HTTP请求设置标题时
this.headers.append("AUTH_TOKEN", token);
I am getting the following error 我收到以下错误
api/Login: 1 Failed to load resource: the server responded with a status of 405 (Method Not Allowed) api /登录:1无法加载资源:服务器以状态405响应(不允许使用方法)
:4200/#/login:1 Failed to load http://localhost:59543/api/Login : Response for preflight has invalid HTTP status code 405. :4200 /#/ login:1无法加载http:// localhost:59543 / api / Login :预检响应具有无效的HTTP状态代码405。
But when I remove the header it works. 但是,当我删除标题时,它可以工作。 Any advice or guidance would be greatly appriciated. 任何建议或指导将不胜枚举。
Your should pass token with token type like, 您应该传递令牌类型为的令牌,
this.headers.append("Authorization", "bearer "+token);
Here, bearer is your token type. 在这里,不记名是您的令牌类型。 It would be another which you set is default. 您将默认设置为另一个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.