How to solve 'Redirect has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header'?


78

I am working on an app using Vue js. According to my setting I need to pass to a variable to my URL when setting change.

<!-- language: lang-js -->

    $.get('http://172.16.1.157:8002/firstcolumn/' + c1v + '/' + c1b, function (data) { 
      // some code...
    });

But when my app hit on URL, it shows the following message.

Failed to load http://172.16.1.157:8002/firstcolumn/2017-03-01/2017-10-26: Redirect from 'http://172.16.1.157:8002/firstcolumn/2017-03-01/2017-10-26' to 'http://172.16.1.157:8002/firstcolumn/2017-03-01/2017-10-26/' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

1
The issue is because the Same Origin Policy is preventing the response from being received due to the originating/receiving domains being different due to the port numbers. To fix this you'll need to return CORS headers in the response from http://172.16.1.157:8002/firstcolumn/.... Exactly how you do that will depend on what server side infrastructure you're using.
Rory McCrossan


In this case, Origin A does GET request to Origin B ; the response redirects to a different location in Origin B. The solution is to trick Chrome into thinking Origin B is Origin A. What if Origin B redirected to Origin C; can we direct to any Origin C, or must we trick Origin C to appear as Origin A? I think we can redirect to any Origin C (for example redirect to a third party single-signon page, or to www.stackoverflow.com ) , regardless of Origin A or the Origin C's Access-Control-Allow-Origin header)
The Red Pea

Answers:


56

In addition to what awd mentioned about getting the person responsible for the server to reconfigure (an impractical solution for local development) I use a change-origin chrome plugin like this:

Moesif Orign & CORS Changer

You can make your local dev server (ex: localhost:8080) to appear to be coming from 172.16.1.157:8002 or any other domain.


2
Im not sure how to set it up, can you explain further? Screenshots would be nice.
Black

@altShiftDev Does this plugin have any options to handle: "Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request."?
tw1742


12

请维护服务器的人员http://172.16.1.157:8002/将您的主机名添加到Access-Control-Allow-Origin主机,服务器应返回类似于以下内容的标头,并带有以下响应-

Access-Control-Allow-Origin: yourhostname:port

@RoryMcCrossan表示来源是本地主机,因此触发了cors。我认为?
user5014677

6

您好,如果我理解正确,您正在将XMLHttpRequest应用于与页面所在域不同的域。因此,出于安全原因,浏览器将其阻止,因为它通常允许来自相同来源的请求。当您想进行跨域请求时,需要做一些不同的事情。有关如何实现此目标的教程是使用CORS

使用邮递员时,它们不受此政策的限制。引用自跨域XMLHttpRequest

常规网页可以使用XMLHttpRequest对象从远程服务器发送和接收数据,但是它们受同一原始策略的限制。扩展不受限制。扩展可以在其起源之外与远程服务器通信,只要它首先请求跨域许可。


6

如果您可以控制服务器,则可以使用PHP:

<?PHP
header('Access-Control-Allow-Origin: *');
?>

最好将其添加到.htaccess文件中,这不仅适用于您添加了此代码段的网站,还适用于整个项目。
网络”

6

如果您在使用Chrome浏览器时遇到此问题,则不需要扩展程序。
从控制台启动Chrome:

chrome.exe --user-data-dir =“ C:/ Chrome开发者会话” --disable-web-security

也许您必须关闭Chrome中的所有标签页并重新启动。


5

到CORS授权添加到使用Apache的头,简单地添加以下线内无论是<Directory><Location><Files><VirtualHost>你的服务器配置(通常位于一个* .conf文件,如httpd.conf中或的apache.conf)的部分,或内一个.htaccess文件:

标头集访问控制允许来源“ *”

然后重新启动apache。

更改标头需要使用mod_headers。默认情况下,Apache中启用了Mod_headers,但是,您可能要确保已启用它。


added into my .htaccess of local project and works like charm, don't forget to reboot your server / mamp / apache, whatever you use.
Cyber

4

You are making a request to external domain 172.16.1.157:8002/ from your local development server that is why it is giving cross origin exception. Either you have to allow headers Access-Control-Allow-Origin:* in both frontend and backend or alternatively use this extension cors header toggle - chrome extension unless you host backend and frontend on the same domain.


嘿,提供的Chrome扩展程序链接已损坏。你能更新答案吗?
OM Bharatiya

3

我在Vue.js和SpringBoot项目中遇到了同样的问题。如果有人使用spring,可以添加以下代码:

@Bean
public FilterRegistrationBean simpleCorsFilter() {  
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();  
    CorsConfiguration config = new CorsConfiguration();  
    config.setAllowCredentials(true); 
    // *** URL below needs to match the Vue client URL and port ***
    config.setAllowedOrigins(Collections.singletonList("http://localhost:8080")); 
    config.setAllowedMethods(Collections.singletonList("*"));  
    config.setAllowedHeaders(Collections.singletonList("*"));  
    source.registerCorsConfiguration("/**", config);  
    FilterRegistrationBean bean = new FilterRegistrationBean<>(new CorsFilter(source));
    bean.setOrder(Ordered.HIGHEST_PRECEDENCE);  
    return bean;  
}   

我在本文中使用Spring Boot和Vue.js构建简单的CRUD应用程序中找到了解决方案


3

尝试在终端中运行此命令,然后再次进行测试。

curl -H "origin: originHost" -v "RequestedResource"

例如:

如果我的originHost平等https://localhost:8081/和我RequestedResource平等https://example.com/

我的命令如下:

curl -H "origin: https://localhost:8081/" -v "https://example.com/"

如果您可以注意到以下一行,那么它应该对您有用。

<access-control-allow-origin:*

希望这可以帮助。



2

或者像这样:

npm install cors

cors = require("cors");
app.use(cors());

1

你不会相信的 请确保添加“。” 在“网址”末尾

我收到与此代码类似的错误:

fetch(https://itunes.apple.com/search?term=jack+johnson)
.then( response => {
    return response.json();
})
.then(data => {
    console.log(data.results);
}).catch(error => console.log('Request failed:', error))

我得到的错误:

 Access to fetch at 'https://itunes.apple.com/search?term=jack+johnson'
 from origin 'http://127.0.0.1:5500' has been blocked by CORS policy:
 No 'Access-Control-Allow-Origin' header is present on the requested
 resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

但是经过大量研究,我意识到问题是我没有从iTunes API文档中复制正确的URL地址。

应该是

https://itunes.apple.com/search?term=jack+johnson.

https://itunes.apple.com/search?term=jack+johnson

注意结尾处的圆点

关于为什么点对引用DNS和字符编码的问题很重要,但有一个巨大的解释,但事实是您可能不在乎。尝试添加可能也适合您的点。

当我添加“。” 一切都像魅力。

我希望它也对您有用。


1

该问题的批准答案无效。

您需要在服务器端代码上设置标头

app.use((req,res,next)=>{
    res.setHeader('Acces-Control-Allow-Origin','*');
    res.setHeader('Acces-Control-Allow-Methods','GET,POST,PUT,PATCH,DELETE');
    res.setHeader('Acces-Contorl-Allow-Methods','Content-Type','Authorization');
    next(); 
})


0

安装:

npm i cors

然后包括cors():

app.get("/list",cors(),(req,res) =>{

});



-1

只需在httpd.conf文件中添加以下文本即可 解决此问题。

标头集访问控制允许来源“ *”


By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.