我有以下角度代码,我也设置了access_token。
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';
import { HttpHeaders } from '@angular/common/http';
import { Headers, Response } from '@angular/http';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
// tslint:disable-next-line:max-line-length
'Authorization': 'bearer zhGMjEFn5SlPYPB4opK57CiPP02MuR-lk10rvYsGU0PcQUyo5U6JHaH5NgdmDpNHSfrkuDLZYIr3xAio_aG0WZbKWM28dgP9BN2i-ERS8PQ97_oXP93AVzHj60RivH5EsfImmEb3mPSSEw68lafAQHe4kQyEptkxTtYlfPczrdQR4hWVOkvA_Hk8JuxFQpUmj0ReRhP5xXfoJcsbOsLpSqcq2xj0GfapcGbvHiHR0hlXTXU9cELnGObXSgDVs1UDpM4pPcFb2CrG7aFCFoULYSe9yBpsn7RepYzomAIrF9hEo2_v_877x7HkVGAMBFd9Ij70jp5DbVumTkZuM9vRG8uDNwaOCsvbsEvZlBjpR4JO0b508vUyKPFctA5O6yzfLKMhpRtcj61HrvWrMqx3BehO-fSM-hmQUd1clH5dD_xX4P9wtR1oPZxNS7bVgUiNnUPkGocqMVS5p0SYyowzz7yKHu8tIpaTAQLPIbePcU6ewtGCBUSzUVZZB7jl5Vte'
})
};
this.Http.get<Teacher>(this.API_URL + 'Teacher/GetTeachers', { headers: this.header }).subscribe(data => {
this.Results = data as Teacher;
console.log('Results' + this.Results[0]);
console.log(this.Results);
});
发送此请求后,我收到以下错误。
请求的资源不支持http方法&#39; OPTIONS&#39; 任何人都可以帮助我。
答案 0 :(得分:0)
我之前遇到过类似的问题,但我忘了在我的服务器端启用cors。
public static void Register(HttpConfiguration config)
{
// Forgot adding below line.
config.EnableCors();
}
您可以在WebApiConfig.cs中检查它吗?
答案 1 :(得分:0)
当我在一个应用程序的后端工作时,我有一个类似的问题,而一位同事正在以角度进行前端工作。我相信我们正在使用基本身份验证。
最终在web.config中添加了Access-Control-Allow-Methods的功能。
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept, Cache-Control, Authorization, authorization" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
注意:以上内容将允许prety很多东西。您可能希望将allow origin和方法限制为所需的内容。
编辑:找到旧代码。我还在global.asax.cs
中添加了Application_BeginRequest方法protected void Application_BeginRequest()
{
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
//These headers are handling the "pre-flight" OPTIONS call sent by the browser
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Authorization");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
希望它有所帮助。
edit2:还发现了一个web.config更改
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>