【问题标题】:ASP.NET5 MVC 6 CORS vue.js request not allowedASP.NET 5 MVC 6 CORS vue.js 请求不允许
【发布时间】:2016-08-25 10:07:24
【问题描述】:

我被困在了某事上。我从 chome postman 应用程序测试我的 api,请求如下:

http://localhost:50000/api/user/user_name/machines

它有效。 我开始在 vue.js 中构建前端并尝试以下操作:

getReports() {
    this.$http
      .get('http://localhost:50000/api/user/user_name/machines', (data) => {
        this.data = data;
      })
      .error((err) => console.log(err))
  }

我当然明白

XMLHttpRequest 无法加载 http://localhost:50000/api/user/user_name/machines。对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。 Origin 'http://localhost:8080' 因此不允许访问。

我之前尝试了一些 react.js 并遇到了同样的问题,所以就像我刚刚添加的那样

services.AddCors();

app.UseCors(builder => builder.AllowAnyOrigin());

到我的 startup.cs 文件,但这次没有运气。我记得它适用于 react.js。我也可以直接从浏览器获取数据——只需访问这个 url。为什么 vue.js 有问题?

我的 startup.cs 文件: http://pastebin.pl/view/b93c9e2c

【问题讨论】:

  • 它在我删除时有效:Vue.http.headers.common['Authorization'] = 'Bearer' + localStorage.getItem('id_token');但为什么标题是你的问题? A 还添加 builder.AllowAnyHeader();但它没有帮助
  • 你删除的那行在哪里?遇到同样的问题,我快疯了!

标签: javascript c# cors asp.net-core-mvc vue.js


【解决方案1】:

您遇到了Cross Origin Request (cors) 限制。这通常发生在您使用完全限定的 url 发出与托管文档不同来源的服务器请求时。

在您的示例中,您在请求中使用了http://localhost:50000/api/user/user_name/machines。如果可能,您可以使用 /api/user/user_name/machines 之类的相对路径,以便根据在浏览器中输入的 url 发出请求。这将确保浏览器不会发送预检请求。

【讨论】:

    猜你喜欢
    • 2015-10-29
    • 2023-03-10
    • 2018-07-28
    • 1970-01-01
    • 2015-03-09
    • 2016-09-15
    • 2019-07-02
    • 2016-11-18
    • 2014-12-20
    相关资源
    最近更新 更多