CORS拒绝GET

时间:2020-07-27 09:46:09

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

我可以登录自己的网站,并通过POST从API获得令牌。 现在,我尝试通过GET使用来自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

和GET

        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 中 在这一本书中,我什至无法登录网站。

Google Chrome浏览器向我显示: 已被CORS政策阻止:对预检请求的响应未通过访问控制检查:它没有HTTP正常状态。

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();
        }
    }

然后,所有问题都已解决。 确保有太多代码。

1 个答案:

答案 0 :(得分:-1)

当应用与后端交互并且应用了CORS政策时,浏览器将首先与后端联系,并说“我正在运行的此应用需要您处理的URL中的某些内容;您未提供该应用的服务向上,所以告诉我您允许应用程序要求这样的URL的特征是什么”-后端列出了特征列表,然后浏览器会查看从X位置下载的正在运行的应用程序是否符合条件

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

应用程序所在的主机和端口号是CORS配置中必须允许的内容,因此,如果您的应用程序是从http:// xyz:1234下载的,并且在其操作过程中,它将通过https向API发出请求:// abc:9876,则该API的配置中必须包含<add name="Access-Control-Allow-Origin" value="http://xyz:1234" />

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

编辑:请注意,IIS不一定支持开箱即用地将CORS放入web.config中-您必须安装the CORS module-如果没有它,则可以编写任何您喜欢的CORS内容在配置文件中,IIS只会忽略它,因为它不知道要查找它,也不知道如何对它采取任何操作

相关问题