【问题标题】:CORS error with Aurelia calling .NET core API 2.0Aurelia 调用 .NET 核心 API 2.0 时出现 CORS 错误
【发布时间】:2018-10-24 12:37:44
【问题描述】:

我收到了 CORS 错误,但我不知道如何修复它。我有一个 Aurelia 应用程序,使用 aurelia-fetch-client 调用 .NET core 2.0 API。我收到以下错误:

无法加载http://localhost:58289/api/info:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin 'http://localhost:8080' 不允许访问。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。

TypeError: 获取失败 在 applyInterceptors (webpack-internal:///./node_modules/aurelia-fetch-client/dist/native-modules/aurelia-fetch-client.js:428:14) 在 processResponse (webpack-internal:///./node_modules/aurelia-fetch-client/dist/native-modules/aurelia-fetch-client.js:411:10) 在 eval (webpack-internal:///./node_modules/aurelia-fetch-client/dist/native-modules/aurelia-fetch-client.js:299:14) 从之前的事件: 在 HttpClient.eval (webpack-internal:///./node_modules/aurelia-fetch-client/dist/native-modules/aurelia-fetch-client.js:287:61) 在 HttpClient.fetch (webpack-internal:///./node_modules/aurelia-fetch-client/dist/native-modules/aurelia-fetch-client.js:273:21) 在 App.callApi (webpack-internal:///app:42:25) 在 CallScope.evaluate (webpack-internal:///./node_modules/aurelia-binding/dist/native-modules/aurelia-binding.js:1578:19) 在 Listener.callSource (webpack-internal:///./node_modules/aurelia-binding/dist/native-modules/aurelia-binding.js:5279:40) 在 Listener.handleEvent (webpack-internal:///./node_modules/aurelia-binding/dist/native-modules/aurelia-binding.js:5288:10) 在 HTMLDocument.handleDelegatedEvent (webpack-internal:///./node_modules/aurelia-binding/dist/native-modules/aurelia-binding.js:3363:20)

请在下面找到我的代码。

aurelia-fetch-client 配置:

const http = new HttpClient().configure(config => {
    config
        .withBaseUrl(environment.apiBaseUrl)
        .withDefaults({
          headers: {
              'Content-Type': 'application/json'
          }
        })
        .withInterceptor({
          request(request: Request) {
            var token = localStorage.getItem('access_token')
            request.headers.append('Authorization', 'Bearer ' + token)
            return request;
          },
          responseError(error){
            return error;
          }
      });
  });

  aurelia.container.registerInstance(HttpClient, http);

调用 API:

callApi(){
    this.httpClient.fetch("/info")
      .then(response => console.log(response));
  }

API 启动配置:

public void ConfigureServices(IServiceCollection services)
{
    string domain = $"https://{Configuration["Auth0:Domain"]}/";
    var allowedCors = Configuration["CorsSite"];

    services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

    }).AddJwtBearer(options =>
    {
        options.Authority = domain;
        options.Audience = Configuration["Auth0:ApiIdentifier"];
    });
    services.AddCors(options => options.AddPolicy("AllowSpecificOrigin", `builder => {`
        builder.AllowAnyOrigin().AllowAnyMethod(); }));
    services.AddMvc();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseCors("AllowSpecificOrigin");
    app.UseAuthentication();
    app.UseMvc();
}

控制器:

[Produces("application/json")]
[Route("api")]
public class InfoController : Controller
{
    // GET api/values
    [HttpGet]
    [Route("Info")]
    public IActionResult Get()
    {
        return Ok("Api V1.0");
    }

    [Route("authorizedInfo")]
    [Authorize]
    [HttpGet]
    public IActionResult GetAuthorized()
    {
        return Ok("Authorized Api V1.0");
    }
}

请暂时忽略授权位。我只是想在 localhost 中访问未经授权的 API 端点,但我被卡住了。我该如何解决我的问题?

【问题讨论】:

    标签: api cors aurelia-fetch-client


    【解决方案1】:

    首先要在 Startup.cs 的 ConfigureServices() 中注册 CORS 功能:

    public void ConfigureServices(IServiceCollection services)
    {
        // Add service and create Policy with options
        services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy",
                builder => builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials() );
        });
    
    
        services.AddMvc(); 
    }
    

    上面的 AddCors() 调用将 CORS 功能添加到 ASP.NET 并创建一个自定义策略,该策略可以按名称在应用程序中重用。还有其他方法可以通过在配置步骤中显式添加策略构建器来完成基本相同的事情,但对我来说这似乎最干净 - 预先定义一个或多个策略,然后应用它。

    一旦定义了策略,就可以应用它。

    您可以通过在 Startup 的 Configure() 方法中调用 app.useCors() 将策略全局应用于应用程序中的每个请求:

    public void Configure(IApplicationBuilder app)
    {
        // ...
    
        // global policy - assign here or on each controller
        app.UseCors("CorsPolicy");
    
        // ...
    
        // IMPORTANT: Make sure UseCors() is called BEFORE this
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
    

    或者您可以将策略应用于各个控制器:

    [EnableCors("CorsPolicy")]
    [ApiExceptionFilter]
    public class AlbumViewerApiController : Controller
    

    谢谢

    【讨论】:

    • 谢谢@Meharwan Singh,我已经尝试了所有这些,但仍然没有运气!
    【解决方案2】:

    以下链接中的答案解决了我的问题。

    Web API 2 CORS IIS Express Debug and No Access-Control-Allow-Origin header

    如果请求中没有原始标头,服务器似乎不会以相应的 Access-Control-Allow-Origin 响应进行响应。同样使用 aurelia-fetch-client 默认值,我希望默认添加原始标头。

    【讨论】:

      猜你喜欢
      • 2021-03-22
      • 2016-06-10
      • 1970-01-01
      • 2021-06-29
      • 2021-08-15
      • 2020-06-17
      • 2020-01-21
      • 2019-10-20
      • 2016-07-18
      相关资源
      最近更新 更多