【问题标题】:Nuxt Axios Access to XMLHttpRequest error - not call .NET webAPi from originNuxt Axios 访问 XMLHttpRequest 错误 - 不从源调用 .NET webAPi
【发布时间】:2021-10-23 04:39:45
【问题描述】:

我正在尝试通过 nuxt axios 向 Localhost API 发出一个简单的请求,但是,无论我在 nuxt 配置文件中尝试做什么,它总是会出现此错误:

访问 XMLHttpRequest 在 'https://localhost:44309/api/api/usuarios/login' 来自原点 “http://localhost:3000”已被 CORS 策略阻止:响应 预检请求未通过访问控制检查:否 请求中存在“Access-Control-Allow-Origin”标头 资源。

我提出这样的要求:

const data= await this.$axios.$post(
        'https://localhost:44309/api/usuarios/login',
        loginObject
      )

这是我的 nuxt.config.js:

publicRuntimeConfig: {
    axios: {
      baseURL: 'https://localhost:44309/api'
    }
  },

  // Axios module configuration: https://go.nuxtjs.dev/config-axios
  axios: {
    proxy: true,
    baseUrl: 'https://localhost:44309/api',
    proxyHeaders: false,
    credentials: false
  },

  proxy: {
    '/api/': { target: 'https://localhost:44309/api', pathRewrite: { '^/api/': '' }, changeOrigin: true }
  }

如您所见,我已经尝试了 n 件事,但没有任何效果,我不再明白了。在我的 .NET webApi 服务器上,我已经在配置中添加了 services.Cors(),没有任何效果。

【问题讨论】:

    标签: vue.js http asp.net-web-api axios nuxt.js


    【解决方案1】:

    这是一个 CORS 问题,因此应该在后端而不是前端解决。

    您的 Nuxt 应用程序是在此处执行 POST 请求的客户端。这种事情可能会通过代理(相当丑陋的解决方案)被黑客入侵,但如果您可以访问后端,请在此处添加 CORS 标头(主要将您的开发和生产 IP 列入白名单),您应该会很好。

    有关这实际上是什么(本质上是安全性)的更多详细信息,Google 将提供很多关于此的内容。

    【讨论】:

    • 但是当我尝试通过 Postman 或类似的方式提出请求时,一切正常。
    • 我已经将 Cors 添加到我的 .net web api 服务中
    • 是的,Postman 工作是完全正常的。仍然是 CORS 问题。您可能以某种方式错误地配置了它。也许用您的 .net 配置创建一个新问题。至少,这不是来自 Nuxt 端代码的错误。 @lukecross
    【解决方案2】:

    如果有人和我有同样的经历,请知道发生的事情很可能是 Cors,就像上面提到的朋友一样。

    您必须在您的 Configuration 方法(在 Startup.cs 中)中创建一个 Cors,并在 Configure 方法中使用您的 Cors。此外,UseCors 需要位于 app.UseRouting 和 app.UseEndpoints 的中间(这基本上是我的问题)。

    以下是基本 Cors 的实现方法:

    public void ConfigureServices(IServiceCollection services)
    {
       services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
                {
                    builder.AllowAnyOrigin();
                    builder.AllowAnyMethod();
                    builder.AllowAnyHeader();
                }));
    }
    
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
       app.UseRouting();
       app.UseCors("MyPolicy");
       app.UseEndpoints(endpoints);
    }
    

    【讨论】:

      猜你喜欢
      • 2021-06-29
      • 2019-05-01
      • 2018-07-27
      • 2021-08-13
      • 1970-01-01
      • 2021-10-20
      • 2019-02-08
      • 2018-12-11
      • 1970-01-01
      相关资源
      最近更新 更多