【问题标题】:Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource (POST request with object)跨域请求被阻止:同源策略不允许读取远程资源(带有对象的 POST 请求)
【发布时间】:2020-06-08 04:38:42
【问题描述】:

我在我的 web api 应用程序中启用了 CORS

var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);

所有请求都运行良好。但是when i pass an object to the post method 我明白了:

跨域请求被阻止:同源策略不允许读取位于http://localhost:44367/api/Users/Create 的远程资源。 (原因:CORS 标头“Access-Control-Allow-Origin”缺失)。

// WORKING
return axios.post(url)
return axios.get(url)


// NOT WORKING

let model = {
    firstName: 'a',
}

return axios.post(url, model);

// or with configuration

let axiosConfig = {
            headers: {
                'Content-Type': 'application/json;charset=UTF-8',
                "Access-Control-Allow-Origin": true,
                "Access-Control-Allow-Credentials": true,
            }
        };

return axios.post(url, model, axiosConfig);

也可以使用邮递员发帖,使用以下正文

//{
//  "model" : {
//      "name":"firstName"
//  }
//}

我在Application_BeginRequest 事件中设置了一个断点,它不会命中。

控制器动作

public ClientResponseModel<User> Create([FromBody]UserAddModel model)
{
   ///.....
}

请求标头

Host: localhost:44367
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:73.0) Gecko/20100101 Firefox/73.0
Accept: */*
Accept-Language: en,en-US;q=0.5
Accept-Encoding: gzip, deflate
Access-Control-Request-Method: POST
Access-Control-Request-Headers: access-control-allow-credentials,access-control-allow-origin,content-type
Referer: http://localhost:44346/Registration.aspx
Origin: http://localhost:44346
Connection: keep-alive

响应头

HTTP/1.1 200 OK
Allow: OPTIONS, TRACE, GET, HEAD, POST
Server: Microsoft-IIS/10.0
Public: OPTIONS, TRACE, GET, HEAD, POST
X-SourceFiles: =?UTF-8?B?QzpcVXNlcnNcYWxpLmtcc291cmNlXEF6dXJlXExlYmFuZXNlTGF3c1xDTVNcYXBpXFVzZXJzXENyZWF0ZQ==?=
X-Powered-By: ASP.NET
Date: Mon, 24 Feb 2020 13:56:15 GMT
Content-Length: 0

非常感谢任何帮助!

【问题讨论】:

    标签: ajax axios asp.net-web-api2 httprequest asp.net-ajax


    【解决方案1】:

    这是典型的 cors 问题,请阅读下面的链接,它可能会帮助您了解为什么会发生此错误。

    https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

    技术,当您的页面域与请求 url 的域不同时,浏览器将阻止您的 xhr 请求。您的服务器应以标头 Access-Control-Allow-Origin: &lt;origin of your client page&gt; | *

    进行响应

    【讨论】:

    • 我了解 cors 的概念,在我的服务器应用程序中启用了 cors,当我通过 post 传递对象时,服务器甚至不会收到请求(在 Application_BeginRequest 处)。请求在prefligh
    • 您的意思是通过 OPTIONS 请求进行预检?它也应该是access-control-allow-origin header的响应
    • 当你发出一个 cors 请求时,浏览器会预检一个选项请求来询问服务器:cors 请求和自定义标头是否允许。
    • 是的,虽然我的应用程序中启用了 CORS,但服务器应该会在 Application_BeginRequest 接收该请求,对吧?
    • 你把 Application_BeginRequest 放在哪里了?发布请求?
    【解决方案2】:

    我最终在我的web.config 中添加了以下内容,以使其无需在 axios 上进行任何自定义配置即可工作:

      <system.webServer>
        <handlers>
          <remove name="ExtensionlessUrlHandler-Integrated-4.0"/>
          <remove name="OPTIONSVerbHandler"/>
          <remove name="TRACEVerbHandler"/>
          <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0"/>
        </handlers>
      </system.webServer>
    

    【讨论】:

      【解决方案3】:

      我遇到了同样的错误。我允许来自应用程序端和服务器端的 cors。但经过搜索,我发现可能存在区域问题,所以我用原始 url 添加了代理 url,它对我有用。这是一个代码:

      var myHeaders = new Headers();
      myHeaders.append("Authorization", "Bearer "+ token);
      
      var requestOptions = {
          
          method: 'GET',
          headers: myHeaders,
          Vary: 'Origin',
      };
      const proxyurl = "https://cors-anywhere.herokuapp.com/";
      const url = "your url";
      
      fetch(proxyurl + url, requestOptions)
          .then(response => response.json())
          .then(result => console.log(result))
          .catch(error => console.log('error', error));
      

      【讨论】:

        【解决方案4】:
        @Bean
        public CorsFilter corsFilter() {
           CorsConfiguration corsConfiguration = new CorsConfiguration();
           corsConfiguration.setAllowCredentials(true);
          corsConfiguration.setAllowedOrigins(Arrays.asList("http://localhost:4200")); 
          corsConfiguration.setAllowedHeaders(Arrays.asList("Origin", "Access-Control,     Allow-Origin", "Content-Type", "Accept", "Authorization", "Origin, Accept", "X-Requested-With", "Access-Control-Request-Method", "Access-Control-Request-Header" )); // this allows all headers
           corsConfiguration.setExposedHeaders(Arrays.asList("Origin", "Content-Type", "Accept", "Authorization", "Access-Control-Request-Allow-Origin", "Access-Control-Allow-Credentials"));
           corsConfiguration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
            UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
            urlBasedCorsConfigurationSource.registerCorsConfiguration("/**",corsConfiguration);
            return new CorsFilter();
        }
        

        我用过它,它对我来说很好用

        【讨论】:

        • 这是用于弹簧靴的
        • 请不要只发布代码作为答案,还要解释您的代码的作用以及它如何解决问题的问题。带有解释的答案通常更有帮助、质量更好,并且更有可能吸引投票
        猜你喜欢
        • 2021-04-04
        • 2014-10-17
        • 2015-07-22
        • 2018-04-20
        • 2014-07-20
        • 1970-01-01
        相关资源
        最近更新 更多