CORS issue Angular4 & C# Web API



我有一个运行在http://localhost:59543/为此,我已通过将以下内容添加到Web.config 中来启用CORS

<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>

我有一个正在运行的角4项目http://localhost:4200/.我使用以下代码进行HTTP请求

登录服务

@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);
}
}

基本服务

@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);
}
}

问题

当我设置HTTP请求的标头时

this.headers.append("AUTH_TOKEN", token);

我得到以下错误

api/Login:1加载资源失败:服务器以405(方法不允许(的状态

:4200/#/login:1加载失败http://localhost:59543/api/Login:飞行前的响应具有无效的HTTP状态代码405。

但当我删除标题时,它就起作用了。如有任何意见或指导,我们将不胜感激。

您应该传递令牌类型为的令牌

this.headers.append("Authorization", "bearer "+token);

这里,持有者是您的代币类型。它将是另一个你设置为默认的。

最新更新