【问题标题】:CORS rejects GETCORS 拒绝 GET
【发布时间】:2020-11-16 15:04:26
【问题描述】:

我可以登录我的网站并通过 POST 从 API 获取令牌。 现在我尝试使用从 API 获取一些数据,但它返回 CORS 错误或 401。我在客户端站点上使用 Vue.js,并使用 ASP.NET Freamwork 4.6 作为 API。 关于 Postman API 的工作。

Postman

我的一些 Vue.js 代码:

GetUsers: function(Page = 1){
        const URI = "http://localhost:5000/api/user?Page="+Page;
        var optionsAxios = {
            headers: {
                'Authorization': 'Bearer ' + localStorage.getItem("user-token"),
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        }
        //var querystring = require('querystring');
        axios.get(URI, optionsAxios).then((result) =>{
                console.log(result.results)
            }).catch(err => {
                console.log(err)
            })
    },

在我添加的 API 中的 Web.config 中

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="http://localhost:8080" />
  </customHeaders>
</httpProtocol>

现在它回来了 跨域请求被阻止:同源策略不允许读取远程资源

如果我使用

const URI = "http://localhost:5000/api/user

和获取

        var querystring = require('querystring');
        axios.get(URI,
            querystring.stringify({
                page: Page
            }),
            optionsAxios).then((result) =>{
                console.log(result.results)
            }).catch(err => {
                console.log(err)
            })

它会返回 错误:请求失败,状态码为 401

编辑

我尝试添加 Web.config

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="http://localhost:8080" /> <-- This one I had before
    <add name="Access-Control-Allow-Headers" value="Content-Type, Accept, Pragma, Cache-Control, Authorization " />
    <add name="Access-Control-Allow-Methods" value="*"/>
    <add name="Access-Control-Allow-Credentials" value="true" />
  </customHeaders>
</httpProtocol>

无论采用何种组合,都没有改变。

我尝试的下一个是

var cors = new EnableCorsAttribute("http://localhost:8080", "*", "*");
config.EnableCors(cors);

WebApiConfig.cs 中 在这个我什至不能在网站上登录。

谷歌浏览器显示: 已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态。

Firefox 显示: 跨源请求被阻止:同源策略不允许读取位于 http://localhost:5000/api/user?Page=5 的远程资源。 (原因:CORS 预检响应未成功)

跨域请求被阻止:同源策略不允许读取位于 http://localhost:5000/api/user?Page=5 的远程资源。 (原因:CORS 请求未成功)。

EDIT2

我修复了这个问题,可能不是最好的方法,但它确实有效。我需要将我找到的所有方法合二为一。

Web.config

<httpProtocol>
  <customHeaders>
    <!--<add name="Access-Control-Allow-Origin" value="http://localhost:8080" />-->
    <add name="Access-Control-Allow-Headers" value="Content-Type, Accept, Pragma, Cache-Control, Authorization " />
    <add name="Access-Control-Allow-Methods" value="*"/>
    <add name="Access-Control-Allow-Credentials" value="true" />
  </customHeaders>
</httpProtocol>

我评论了允许来源。 在 WebApiConfig.cs

中添加
var cors = new EnableCorsAttribute("http://localhost:8080", "*", "*");
config.EnableCors(cors);

在 Global.asax/Global.asax.cs 中

protected void Application_BeginRequest(Object sender, EventArgs e)
    {
        // Preflight request comes with HttpMethod OPTIONS
        if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
        {
            HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
            // The following line solves the error message
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            // If any http headers are shown in preflight error in browser console add them below
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Pragma, Cache-Control, Authorization ");
            HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
            HttpContext.Current.Response.End();
        }
    }

然后一切都修复了。 肯定是代码太多了。

【问题讨论】:

  • 应用程序是从哪个 URL 下载的?
  • 没有下载
  • 这个错误可能是因为你的令牌@DonQnei
  • 我在 Postman 中尝试过这个令牌,它奏效了。
  • 未下载 - 它是如何进入浏览器的?即使浏览器从 localhost 上运行的 Web 服务器下载应用程序,它仍在下载该应用程序..

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


【解决方案1】:

当应用与后端交互并且应用了 CORS 策略时,浏览器将首先联系后端并说“我正在运行的这个应用需要来自你处理的 URL 的东西;你没有为应用提供服务起来,所以告诉我你允许应用程序请求这样的 url 的特性” - 后端给出特性列表,然后浏览器查看它正在运行的应用程序,它从位置 X 下载,是否符合标准.

如果没有,应用程序会遇到拒绝而没有进一步处理 - 也就是说,如果浏览器对服务器说 OPTIONS /someurl 并返回不包含任何 CORS 标头的响应,或者包含与发出的请求不匹配的内容,然后 *browser( 将向您的应用程序发出 401;这与服务器无关 - 服务器甚至不知道您正在尝试 GET /someurl - 它所看到的只是由浏览器首先发出的OPTIONS /someurl,如果它对 OPTIONS 的响应中没有包含 CORS 标头,则浏览器甚至不会尝试代表您的应用执行 GET

应用托管的主机和端口号是 CORS 配置中必须允许的,因此如果您的应用是从 http://xyz:1234 下载的,并且在其运行期间,它将向 https 的 API 发出请求://abc:9876,那么该 API 的配置必须在其配置中包含 &lt;add name="Access-Control-Allow-Origin" value="http://xyz:1234" /&gt;

CORS 还可以应用于其他方面,例如应用程序尝试用于访问后端的 HTTP 方法:https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Methods

编辑:请注意,IIS 不一定支持将 CORS 放入 web.config 开箱即用 - 您必须安装 the CORS module - 没有它,您可以在配置文件和 IIS 将忽略它,因为它不知道查找它或如果找到它如何对其采取任何操作

【讨论】:

  • 我有...即使我在上面用这一行发布了 API Web.config 代码的一部分。我可以使用 POST 并且 CORS 不会拒绝这个,但我不能使用 GET。
  • 然后检查您的 CORS 策略是否允许 GET 和 POST,例如将 Access-Control-Allow-Methods: * 放入您的 CORS 配置中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-13
  • 2017-01-14
  • 2021-03-27
  • 2016-04-25
  • 2019-01-18
  • 2021-07-11
相关资源
最近更新 更多