Cross-Origin 请求被阻止:同源策略不允许读取远程资源(POST 请求 object)
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource (POST request with object)
我在我的 Web api 应用程序中启用了 CORS
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
所有请求都工作正常。但是 when i pass an object to the post method
我明白了:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:44367/api/Users/Create. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
// 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);
使用 postman 发帖也正常,以下 body
//{
// "model" : {
// "name":"firstName"
// }
//}
我在 Application_BeginRequest
事件中设置了一个 break-point,它不会命中。
控制器动作
public ClientResponseModel<User> Create([FromBody]UserAddModel model)
{
///.....
}
请求Header
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
回应Header
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
非常感谢任何帮助!
这是典型的cors问题,阅读下面的link,可能会帮助您理解为什么会出现此错误。
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
技术,当您的页面域与请求域不同时,浏览器将阻止您的 xhr 请求 url。您的服务器应以 header Access-Control-Allow-Origin: <origin of your client page> | *
响应
我最终在 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>
我遇到了同样的错误。我允许来自应用程序端和服务器端的 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));
@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();
}
我用过这个,对我来说效果很好
我在我的 Web api 应用程序中启用了 CORS
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
所有请求都工作正常。但是 when i pass an object to the post method
我明白了:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:44367/api/Users/Create. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
// 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);
使用 postman 发帖也正常,以下 body
//{
// "model" : {
// "name":"firstName"
// }
//}
我在 Application_BeginRequest
事件中设置了一个 break-point,它不会命中。
控制器动作
public ClientResponseModel<User> Create([FromBody]UserAddModel model)
{
///.....
}
请求Header
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
回应Header
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
非常感谢任何帮助!
这是典型的cors问题,阅读下面的link,可能会帮助您理解为什么会出现此错误。
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
技术,当您的页面域与请求域不同时,浏览器将阻止您的 xhr 请求 url。您的服务器应以 header Access-Control-Allow-Origin: <origin of your client page> | *
我最终在 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>
我遇到了同样的错误。我允许来自应用程序端和服务器端的 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));
@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();
}
我用过这个,对我来说效果很好