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

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.

This question is related to javascript jquery vuejs2

The answer is


Thanks all, I solved by this extension on chrome.

Allow CORS: Access-Control-Allow-Origin


Ask the person maintaining the server at http://172.16.1.157:8002/ to add your hostname to Access-Control-Allow-Origin hosts, the server should return a header similar to the following with the response-

Access-Control-Allow-Origin: yourhostname:port

To add the CORS authorization to the header using Apache, simply add the following line inside either the <Directory>, <Location>, <Files> or <VirtualHost> sections of your server config (usually located in a *.conf file, such as httpd.conf or apache.conf), or within a .htaccess file:

Header set Access-Control-Allow-Origin "*"

And then restart apache.

Altering headers requires the use of mod_headers. Mod_headers is enabled by default in Apache, however, you may want to ensure it's enabled.


You won't believe this, Make sure to add "." at the end of the "url"

I got a similar error with this code:

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))

The error I got:

 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.

But I realized after a lot of research that the problem was that I did not copy the right URL address from the iTunes API documentation.

It should have been

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

not

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

Notice the dot at the end

There is a huge explanation about why the dot is important quoting issues about DNS and character encoding but the truth is you probably do not care. Try adding the dot it might work for you too.

When I added the "." everything worked like a charm.

I hope it works for you too.


I had the same problem in my Vue.js and SpringBoot projects. If somebody work with spring you can add this code:

@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;  
}   

I found solution in this article Build a Simple CRUD App with Spring Boot and Vue.js


You can solve this temporarily by using the Firefox add-on, CORS Everywhere. Just open Firefox, press Ctrl+Shift+A , search the add-on and add it!


When you have this problem with Chrome, you don't need an Extension.
Start Chrome from the Console:

chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security

Maybe you have to close all Tabs in Chrome and restart it.


you have to customize security for your browser or allow permission through customizing security. (it is impractical for your local testing) to know more about please go through the link.
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS


Simply by adding below text in the httpd.conf file will solve this issue.

Header set Access-Control-Allow-Origin "*"


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

Just put "https" .


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.


If you have control over your server, you can use PHP:

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

The approved answer to this question is not valid.

You need to set headers on your server-side code

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

Do specify @CrossOrigin(origins = "http://localhost:8081") in Controller class.


Hello If I understood it right you are doing an XMLHttpRequest to a different domain than your page is on. So the browser is blocking it as it usually allows a request in the same origin for security reasons. You need to do something different when you want to do a cross-domain request. A tutorial about how to achieve that is Using CORS.

When you are using postman they are not restricted by this policy. Quoted from Cross-Origin XMLHttpRequest:

Regular web pages can use the XMLHttpRequest object to send and receive data from remote servers, but they're limited by the same origin policy. Extensions aren't so limited. An extension can talk to remote servers outside of its origin, as long as it first requests cross-origin permissions.


install:

npm i cors

Then include cors():

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

});


Try running this command in your terminal and then test it again.

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

Eg:

If my originHost equals https://localhost:8081/ and my RequestedResource equals https://example.com/

My command would be as below:

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

If you can notice the following line then it should work for you.

< access-control-allow-origin: *

Hope this helps.


Or like this :

npm install cors

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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to vuejs2

How can I go back/route-back on vue-router? Change the default base url for axios How to change port number in vue-cli project How to solve 'Redirect has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header'? vuetify center items into v-flex Vuejs: Event on route change Vuex - Computed property "name" was assigned to but it has no setter Vuex - passing multiple parameters to mutation How to listen to the window scroll event in a VueJS component? How to acces external json file objects in vue.js app