Axios: Getting 'Cross-Origin Request Blocked' on a GET request

Created on 23 Apr 2017  ·  143Comments  ·  Source: axios/axios

Summary

I'm making a GET request to 4chan's API for retrieving threads from a board. This is my code:

const board = this.props.routeParams.tag;
var config = {
    headers: {'Access-Control-Allow-Origin': '*'}
};
axios.get('https://a.4cdn.org/' + board + '/threads.json', config)
    .then(function (response) {
        console.log(response.data);
});

I receive the following warning:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://a.4cdn.org/a/threads.json. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
As seen above, I have added the relevant header, but it does not solve the issue. I made the same request from my terminal using cURL and it worked fine.

Context

  • axios version: e.g.: v0.16.0
  • Environment: e.g.: node v6.9.4, Firefox 51.0.1, Ubuntu 14.04

Most helpful comment

Any news on this? I'm pretty much in the same boat...

All 143 comments

cURL does not enforce CORS rules. Those rules are enforced by browsers for security purposes.

When you mention that you added the relevant header, I assume you mean you added those headers to the request. Actually, the header is expected in the response headers from the server, indicating that the resource is allowed to be accessed by other websites directly.

FYI, CORS - Cross Origin Resource Sharing. Since your API does not support it, you have two options -

  1. Use a proxy server on the same domain as your webpage to access 4chan's API or,
  2. Use a proxy server on any other domain, but modify the response to include the necessary headers.

I'd like to vote to close this issue as "Not an issue".

Thank you for the suggestion. I have updated my code to route the request through a proxy:

axios.get('https://a.4cdn.org/a/threads.json', {
    headers: {
      'Access-Control-Allow-Origin': '*',
    },
    proxy: {
      host: '104.236.174.88',
      port: 3128
    }
    }).then(function (response) {
        console.log('response is : ' + response.data);
    }).catch(function (error) {
        if (error.response) {
          console.log(error.response.headers);
        } 
        else if (error.request) {
          console.log(error.request);
        } 
        else {
          console.log(error.message);
        }
    console.log(error.config);
});

However, I'm still getting this error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://a.4cdn.org/a/threads.json. (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘https://boards.4chan.org’).

I have searched through various forums and questions on Stack Overflow and I can't seem to find any solution to this. It would be appreciated if someone could provide some insight.

Any news on this? I'm pretty much in the same boat...

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://a.4cdn.org/a/threads.json. (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘https://boards.4chan.org’).

This is because https://a.4cdn.org and https://boards.4chan.org are considered to be different domains. The difference is in a and boards

I'm also getting same issue. Can anyone please help me on this

saaaaame

As a temporary solution you can use this : https://chrome.google.com/webstore/detail/cors-toggle/omcncfnpmcabckcddookmnajignpffnh

I did not find anything better for now ..

@PetitBateau I'm not sure how the Chrome extension would help sending requests through axios.

@adl1995 It did the trick for me ;)

A Chrome extension helps only for those who have the extension. Depending on Chrome extension in production is not a good idea, as not everyone has that extension.

That's why i said it was a temporary solution. And of course for a dev environment.

Access-Control-Allow-Origin is a response header, not request header:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin

axios.get(url, { headers: {'Access-Control-Allow-Origin': *} } ) means nothing!

try
axios.get(url, { crossdomain: true })

@ronnin For the record, I tried out your solution, but it doesn't work.

The remote service to which you are making your AJAX request does not accept cross origin AJAX requests from your domain. One thing you could do if you have access to your website server-side codebase, is to create a controller action there (assuming you are using an MVC) and then use it to consume the remote service. You can then make AJAX requests to your controller action. A bonus to this approach is that you could run additional checks before contacting the remote service, formatting its response and even caching it.

i always find reference to that MDN document not very helpful. its a long document and it doesnt directly address the question at hand. what do i do if i dont have access to the server side codebase and want to access this API?

My solution is to create my own api on my domain server to access any foreign api that doesnt allow cross-origin requests, I call it my repeater api.

@JigzPalillo Can you share the approach or code? I'm pretty much stuck! :(

Normally this would work, but in the case that it doesn't and you don't have any access to that domain...

axios.get('https://www.notmydomain.com/1511.json')
    .then(function (response) {
        console.log(response.data);
});

What I did was create a repeater on my server

axios.get('https://www.mydomain.com/repeater.php?url=https://www.notmydomain.com/1511.json')
    .then(function (response) {
        console.log(response.data);
});
/* repeater.php */
function collect_data($url){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //remove on upload
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_VERBOSE, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, false);
    curl_setopt($ch, CURLOPT_REFERER, "https://www.notmydomain.com");
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    $result = curl_exec($ch);
    echo curl_error($ch);
    curl_close($ch);
return($result);
}
echo collect_data($_GET["url"]);

The server needs to respond with CORS headers on the options call. If you are using nodejs/express, you can fix this for all endpoints with:

app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  next();
});

But that's a little loose. Probably want to tighten up for production.

I have long solved that problem though. The server belongs to a 3p service and therefore out of my control. I simply proxied it instead. All is well on that front.

Thanks

@steveswork same here, server belongs to a 3p service, pretty sad that I can use ajax, request.js but not axios which i prefer 👎

@adl1995 do happen to be able to fix this problem yet? I totally confuse how to handle this error

it's 2018 now, is there any update?

@challenger532 Nope Still not.

The error is still prevalent.

My advice: use a different library.

Okay, this kinda solved my problem. You see, I'm working with vuejs and Laravel... i set up my Laravel web route in php as follows:

Route::get('distancematrix/{source}/{destination}', function($source,$destination){
 $url = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=$source&destinations=$destination&key=YOUR_API_KEY";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);

return json_decode($response, true);
});

then vuejs file i simply used axios to send a request to my route:

axios.get("distancematrix/place_id:${this.place.source}/place_id:${this.place.destination}").then(response => {
                    console.log('====================================')
                    console.log(response.data)
                    console.log('====================================')
   })

and voila, it works fine.

if use Laravel, addition function:

header('Access-Control-Allow-Origin: *');

to controller or route before return
Example:
Route::get('post',function(){ $jav = Blog::all(); header('Access-Control-Allow-Origin: *'); return $jav; });
Sorry for my English. Hope this can help you.

I use vue.js (localhost port 8080 ) and Flask for my API (localhost port 5000)

I simply had to make small change in my api code (Flask on port 5000) .
I added flask extension flask-CORS and modified my code to use it.
Before:

from flask import Flask, request
import json
app = Flask(__name__)

After:

from flask import Flask, request
import json
from flask_cors import CORS
app = Flask(__name__)
CORS(app)

After this it worked and I could use my API.
So it is not really axios issue, but API problem and you get warning from Firefox not from calling axios.get function.

By setting the headers and proxy options, I got instead the Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource..

But I was able to get around that with this extension: https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en .

Sadly, that worked only yesterday and not today...I've been trying to figure out the hell why

Proxy requests using Webpack dev server to avoid _cors_ in development mode

In your webpack.config file add

"devServer":{
  "proxy": {
    "/api": {
    "target": 'https://my-target.com',
    "pathRewrite": { '^/api': '' },
    "changeOrigin": true,
    "secure": false
    }
  }
}

The above example will proxy the request
axios.post(/api/posts/1 ... . . . .
to https://my-target.com/posts/1

The above Git example, u need to change like this in your request

axios.get('/api/a/threads.json', {
    headers: {
           //  if u have some headers like this
       //  'Authorization': ' Basic //////some values'
    },
    }).then(function (response) {
        console.log('response is : ' + response.data);
    }).catch(function (error) {
        if (error.response) {
          console.log(error.response.headers);
        } 
        else if (error.request) {
          console.log(error.request);
        } 
        else {
          console.log(error.message);
        }
    console.log(error.config);
});

In webpack.config file ........

"devServer":{
  "proxy": {
    "/api": {
    "target": 'https://a.4cdn.org',
    "pathRewrite": { '^/api': '' },
    "changeOrigin": true,
    "secure": false
    }
  }
}

the modified webpack config proxy will change your request like this..

u can see this in chrome dev tool REQUEST HEADERS
https://a.4cdn.org/a/threads.json 

u can use multiple paths in devServer proxy like this
In webpack.config file ........

"devServer":{
  "proxy": {
    "/api": {
    "target": 'https://a.4cdn.org',
    "pathRewrite": { '^/api': '' },
    "changeOrigin": true,
    "secure": false
    },
    "/login": {
    "target": 'https://github.com', // for example
    "pathRewrite": { '^/login': '' },
    "changeOrigin": true,
    "secure": false
    },
    "/post": {
    "target": 'https://facebook.com', // for example
    "pathRewrite": { '^/post': '' },
    "changeOrigin": true
    }
  }
}

Use if u need

    "changeOrigin": true,
    "secure": false

I spent hours to fix it and seems like no help everywhere. the simple and fast way is to add a chrome extension called Allow-Control-Allow-Origin*. https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en

will help only you, but how about other people?

trying Vue and axios I obviously got the same issue.

Just tried the solution provided by sundar6445 and it works perfectly.
The webpack config file I modified is in /config/index.js. I prefered to modify this one since referenced in /build/webpack.dev.conf.js

In it you find

module.exports = {
  dev: { 
...
proxyTable: {},

As described by sundar, change the proxyTable by for instance something like

proxyTable: ({
      '/events': {
        "target": 'http://localhost:3000',
        "changeOrigin": true,
        "secure": false
      }
    }),

which means that everything starting by /events will be routed to http://localhost:3000/events. No 'pathRewrite' in my case, relative url will be the same.

and of course, don't forget to remove the full URL in your Vue component. I had:

  mounted () {
    axios.get('http://localhost:3000/events/nb')
      .then(result => {
        this.new_et_nb = result.data
        console.log('*******' + JSON.stringify(result) + ', ' + result.data)
      }, error => {
        console.error(error)
      })
  }

it becomes:

  mounted () {
    axios.get('/events/nb')
      .then(result => {
        this.new_et_nb = result.data
        console.log('*******' + JSON.stringify(result) + ', ' + result.data)
      }, error => {
        console.error(error)
      })
  }

and it works perfectly well. Thanks to @sundar6445

Hope this helps

I know this is marked closed, but I wanted to point something out. Sometimes this error will appear on the client side if your API Key is either expired or being used by someone else.

This might go without saying of more experienced developers but for those people new to coding, make sure you have a unique API Key. Not all APIs require unique keys, but if they do, you will certainly need it. Refer to the API documentation for your specific API to see what they require.

There is no option as crossDomain inside the Axios. Please study the source-code before giving/using wrong clues.

You cannot execute JavaScript on a client (without disabling CORS and making you a target for XSS) to retrieve information from another site.

This is to prevent you from gaining access to a client's browser and potentially draining their bank accounts or posting to some site without their permissions. The same goes for scraping sites (which is essentially what the op is trying to do).

You can scrape the web (i.e., fetch data) using a server with a CORS module, and proxy via that server.

I think this header config will solve this issue.

headers: { 'content-type': 'application/x-www-form-urlencoded' }

Thanks

I know this sounds cliche, but my solution to this problem has been creating a custom api to handle this calls.

The problem is not with axios. The issue is with the server. When you serve up data you must add the following headers, before sending it.

Access-Control-Allow-Origin must be set to *

Access-Control-Allow-Headers must be set to Origin, X-Requested-With, Content-Type, Accept

Source : CORS error while making axios.get call

Referring to these answer, i added those lines to my backend express server, like so :

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "http://127.0.0.1:8080"); //My frontend APP domain
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    next();
});`

source : CORS on ExpressJS

And everything works fine for me, without any additional configuration on axios or in the frontend, so it's really not an axios problem but a lack of server side header configuration.

Finally, i think this other answer on stackoverflow, cover pretty well the subject :

How to avoid the CORS preflight
How to use a CORS proxy to get around “No Access-Control-Allow-Origin header” problems
How to fix “Access-Control-Allow-Origin header must not be the wildcard” problems

hope it helps.

if you want to fetch data from a third party api or url that has a issue with its CORS header(missing or contains multiple values) I think the only solution for this is use this link
"https://cors-anywhere.herokuapp.com/"
I use the link for small projects but for big projects you may want to create your own api to handle the calls and creating the api you can use the open source project https://github.com/Rob--W/cors-anywhere/ .

This one will work:

axios.get(`${'https://cors-anywhere.herokuapp.com/'}https://a.4cdn.org/a/threads.json`)
.then(res => {
  console.log(res)
})

I bumped into this problem some time ago while creating 4webm and 4chan-list-webm

It's worth noting that if you make a browser plugin, you don't need to play with the headers to hit the API. Maybe if we summon @moot he'll enable CORS :smile:

crossdomain: true

I had to enable the port '8080' on the backend CORS and it then worked.

secure

webpack documentation to a better understanding: https://webpack.js.org/configuration/dev-server/#devserver-proxy

If you are using laravel or lumen for your backend API. And you are using barryvdh/laravel-cors package already. The solution is to set your cors.php config as the header, method and origin part as this
'allowedOrigins' => ['*'], 'allowedHeaders' => ['*'], 'allowedMethods' => ['*'],
Hopefully it solves someone's issue

If you do it in safari it takes no time, Just enable the developer menu from Preferences >> Advanced, and select "Disable Cross-Origin Restrictions" from the develop menu. If you want local only, then you only need to enable the developer menu, and select "Disable local file restrictions" from the develop menu.

and in Chrome for OSX open Terminal and run:

$ open -a Google\ Chrome --args --disable-web-security --user-data-dir

--user-data-dir required on Chrome 49+ on OSX

For Linux run:

$ google-chrome --disable-web-security
Also if you're trying to access local files for dev purposes like AJAX or JSON, you can use this flag too.

-–allow-file-access-from-files
For Windows go into the command prompt and go into the folder where Chrome.exe is and type

chrome.exe --disable-web-security
That should disable the same origin policy and allow you to access local files.

Tried all the solution mentioned above. nothing works.
finally found one - https://github.com/expressjs/cors
i hope it helps you guys

The main issue is the difference between server requests and client requests.

When you're making requests via the client (aka most of the time, a browser) you are at the mercy of the browser software. The standard for browser software is to prevent any attempts at malicious activity that may or may not come from your own software.

If you are making a request from your own server (aka not a browser client), then the given is that for the code you have written yourself, no one (depending on your server settings) can access nor control it, and you know what kinds of requests are outgoing so there are no concerns for network calls occurring outside of your environment or your knowledge.

That's why browsers are strict about cross origin requests, specifically since once your public code is on the client, you have less control over who sees it / who can manipulate it. In the case that your frontend application is compromised and some malicious software is able to conduct network calls off your code at the expense of your visitors/users, they want to ensure that it cannot happen. Therefore, your mydomain.com cannot make calls to allyourdataarebelongtome.com just in case you didn't mean for it to happen.

The solution here is not that cross domain requests are not working - it's that either your own server is preventing this and you need to accommodate this circumstance in accepting your origin domain, or that the third party server you're trying to make API calls to has some other method of authentication/authorization on top of that cross domain request.

@mddanishyusuf Solution worked for me.

I think this header config will solve this issue.

headers: { 'content-type': 'application/x-www-form-urlencoded' }

Thanks

Thanks! ;)

From here : https://github.com/axios/axios I've realized that they doesn't put full url to axios url request.

So I try and solved this by creating my own API on my site. I just sent request like this

axios.get('/sample/request')

then http://127.0.0.1:8080/sample/request will send another request to https://a.4cdn.org/ and return responses to axios as json.

It's work for me, hope it can help you

https://github.com/axios/axios/issues/853#issuecomment-408218917 worked with fetch API and a .NET 4.5 web API.

As I understand the problem is that request is sent from loclahost:3000 to loclahost:8080 and browser rejects such requests as CORS. So solution was to create proxy and browser will handle requests as they are gone from one server.
Correct me if I'm wrong

My solution was :
import proxy from 'http-proxy-middleware'
app.use('/api/**', proxy({ target: "http://localhost:8080" }));

I was with the same problem and I solve it installing 'cors' in my backend (Express).

Run:
npm install cors

Then just set this:

var cors = require('cors');
app.use(cors());

Thank's @fernandoruch, this is working with my nodejs server

I had same problem and solved it

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  next();
});

worked at first, but then it stopped and i couldnt figure out why.

then I realized that I moved all my code to another file so I need to use router :

router.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  next();
});

Hi,

Any update on this issue, I'm using .net core 2.1 and axios 0.18.

Thanks.

I don't think the issue is in axios, the issue is in your back-end server.

For me I have an architecture with Flask on back-end and using axios in Vue.JS, only thing I had to do on my Flask server is:

...
from flask_cors import CORS
...
CORS(app)

This shouldn't go to production though, you can also have a cross origin allow list at the nginx level. I read through this, might be helpful.

As a temporary solution you can use this : https://chrome.google.com/webstore/detail/cors-toggle/omcncfnpmcabckcddookmnajignpffnh

I did not find anything better for now ..

Bad idea

I ran into this issue when I attempted to simply make a axios.get() request to the Darksky weather api. When I read through Darksky's FAQ page I found a question regarding this same exact problem, they answered by saying that they used this as a security measure to prevent unintended malicious access to their information and suggested creating a proxy to access their database.

I made the following change to my package.json file (I'm using create-react-app):

{
  "proxy": "https://api.darksky.net/forecast/[myKey]
}

myKey was provided to me by Darksky to access their data.

This was a super simple fix and worked for me! I would suspect that many api services are going to start using this as a security measure. Hopefully my solution can help others with similar issues.

In summary: create a proxy.

Thank's @fernandoruch . It works for me when I add it to app.js of my node.js server

var cors = require('cors');
app.use(cors());
import axios from 'axios'
import jsonpAdapter from 'axios-jsonp'

axios.get(`${url}`, { adapter: jsonpAdapter })
        .then(result => {
            console.log('Status Code: ' + result.status)
        })
        .catch(error => console.log('Request failed'))

JSONP (JSON with Padding or JSON-P) is used to request data from a server residing in a different domain than the client. JSONP enables sharing of data bypassing same-origin policy.

I just use jquery's $.get for external api calls.

if you want to fetch data from a third party api or url that has a issue with its CORS header(missing or contains multiple values) I think the only solution for this is use this link
"https://cors-anywhere.herokuapp.com/"
I use the link for small projects but for big projects you may want to create your own api to handle the calls and creating the api you can use the open source project https://github.com/Rob--W/cors-anywhere/ .

This one will work:

axios.get(`${'https://cors-anywhere.herokuapp.com/'}https://a.4cdn.org/a/threads.json`)
.then(res => {
  console.log(res)
})

@yasincidem - You are an absolute diamond for this suggestion. Cheers - i've followed many trails across the web in search of a solution and yours is the first that has worked for my particular scenario.

I just came a cross this issue. I had {withCredentials: true} (a copy and paste from my other API) for this particular 3rd party API to work I simply had remove {withCredentials: true}

This solution work for me

axios.get(myurl, {
    crossDomain: true
}).then(res => { 
    console.log(res);
}).catch(error => {
    console.log('error', error);
})

reference https://stackoverflow.com/questions/42422494/cross-domain-at-axios

if you want to fetch data from a third party api or url that has a issue with its CORS header(missing or contains multiple values) I think the only solution for this is use this link
"https://cors-anywhere.herokuapp.com/"
I use the link for small projects but for big projects you may want to create your own api to handle the calls and creating the api you can use the open source project https://github.com/Rob--W/cors-anywhere/ .

This one will work:

axios.get(`${'https://cors-anywhere.herokuapp.com/'}https://a.4cdn.org/a/threads.json`)
.then(res => {
  console.log(res)
})

Extraordinary it works !!!

we encountered this issue as well when switching to axios
our setup is webpack + devServer (with proxy) + axios

the problem was that we used our full api url as baseURL in axios instead of just '/api' (the proxy does the mapping via the target attribute)

In my opinion this might be due to our own mistakes. I am experiencing the same problem as above. 2 days I took the time to look for this problem. it turns out it's just a small problem that I found. the url address I entered is not in accordance with the parse documentation. and now axios works perfectly on my angular 7

Check if the flask or other server has CORS enabled .
Also check if the server address is correct .I was stuck just because i forgot to add the port of the server .
axios.get('http://localhost:5000/jsonshow')
.then(response => (this.array= response))

Change "localhost:3000" to "http://localhost:300" work fine with me(make sure enable cors at serverside)

Change "localhost:3000" to "http://localhost:300" work fine with me(make sure enable cors at serverside)

if you are running on port 300 and not 3000.

in VueJS you can create a vile called vue.config.js at the root of the project if it doesn't exist and add something like

module.exports = {
  devServer: {proxy: 'http://localhost:3000'}
}

Then your Axios call should look like

axios.get('/api/say_hello', {})

if you want to fetch data from a third party api or url that has a issue with its CORS header(missing or contains multiple values) I think the only solution for this is use this link
"https://cors-anywhere.herokuapp.com/"
I use the link for small projects but for big projects you may want to create your own api to handle the calls and creating the api you can use the open source project https://github.com/Rob--W/cors-anywhere/ .

This one will work:

axios.get(${'https://cors-anywhere.herokuapp.com/'}https://a.4cdn.org/a/threads.json)
.then(res => {
console.log(res)
})

This one worked for me! Thanks!

Try this one :

import Vue from 'vue';
import App from './App.vue';
import router from './router';
import axios from 'axios';

Vue.config.productionTip = false;

// ======================
axios.defaults.withCredentials = false;
axios.defaults.proxy = {
  host: 'http://localhost',
  port: 5000,
};
// ======================
new Vue({
  router,
  render: (h) => h(App),
}).$mount('#app');

if you want to fetch data from a third party api or url that has a issue with its CORS header(missing or contains multiple values) I think the only solution for this is use this link
"https://cors-anywhere.herokuapp.com/"
I use the link for small projects but for big projects you may want to create your own api to handle the calls and creating the api you can use the open source project https://github.com/Rob--W/cors-anywhere/ .

This one will work:

axios.get(`${'https://cors-anywhere.herokuapp.com/'}https://a.4cdn.org/a/threads.json`)
.then(res => {
  console.log(res)
})

Saving my time, thank you a lot!

@ronnin For the record, I tried out your solution, but it doesn't work.

What? Really? For me it definitely worked...
For the GET method, works like a charm!

Here is the example I made using a public API, based on @ronnin comment:
axios.get('https://world.openfoodfacts.org/api/v0/products', { crossdomain: true }) .then(function (response) { console.log(response.data); })

it's 2019 now, is there any update? 😃

@ronnin For the record, I tried out your solution, but it doesn't work.

Men, who are in trouble, are not well acknowleged with CORS, and should read the article @seungha-kim mentioned earlier: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

As summary:

  1. remote resources you requested, if not on the same host as requesting from (so-called: origin), must provide additional CORS header along with the resource, aka. Access Control Allow: host(origin), headers, methods, etc.
  2. requesting by browsers or curl with header 'Access-Control-Request-Method' , requesting with method 'OPTIONS' will be tried first automatically before the intended method: 'GET', 'POST', etc.
    which means the handlers of remote resources must handle the method 'OPTION' specially. for example(nginx):
    ```groovy
    location /the-remote-resource {
    if ($request_method = 'OPTIONS') {
    add_header 'Access-Control-Allow-Origin' $http_origin;
    add_header 'Access-Control-Allow-Headers' 'DNT,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
    add_header 'Access-Control-Allow-Methods' 'OPTIONS, GET, POST, PUT, PATCH, DELETE';
    add_header 'Access-Control-Allow-Credentials' true;
    add_header 'Access-Control-Max-Age' 1728000; # 20d
    add_header 'Content-Type' 'text/plain charset=UTF-8';
    add_header 'Content-Length' 0;
   return 204;
  }
 // more ...

}
```

  1. as mentions above, I did't use value * to each Access-Control-Allow-* headers.
    value *, has many restrictions.
    a. value * to Access-Control-Allow-Origin,Access-Control-Allow-Headers,Access-Control-Allow-Methods cannot works with Access-Control-Allow-Credentials=true. if cookie is required with request, you'll need Access-Control-Allow-Credentials=true
    b. only * is valid, *.google.com is INVALID
  1. Access-Control-Allow-Headers is a list of headers of your request possibly along with. existence of some headers which not listed in it will get you blocked. just check and opt the headers into Access-Control-Allow-Headers

  2. the trouble is mostly not in the client(browser, your client app), but in the server requested resource located.

  3. talk to your server-side dev mate

Hope it's helpful

@ronnin : If I understand correctly from your points, it means if my GET request is requesting resource from some server which they don't enabled CORS, basically there's nothing we can do from front end right?

@ronnin : If I understand correctly from your points, it means if my GET request is requesting resource from some server which they don't enabled CORS, basically there's nothing we can do from front end right?

Use the following app below to make ur requests working

It worked for me even though the server did not enable CORS

https://cors-anywhere.herokuapp.com/

Usage :

url = https://cors-anywhere.herokuapp.com${url};
`

@ronnin : If I understand correctly from your points, it means if my GET request is requesting resource from some server which they don't enabled CORS, basically there's nothing we can do from front end right?

if my GET request is requesting resource from some server which they don't enabled CORS, basically there's nothing we can do from front end through XHR request(aka. AJAX request) directly. Yes!
It's the browser which follows the protocol and rejects your request.
but, you can get the resource by tranditional browser request, like location.href, iframe, form.action

Mostly, we set up a self-own reverse proxy server, (like nginx), with self-controlled server side to solve the problem requesting 3-rd resource without CORS enabled.
The Heroku App, @ndjerrou mentioned, is the case.

we have self-driving cars and AI but still struggling with CORS

I managed to solve this using heroku as a proxy.

Here is my code;

fetch("https://cors-anywhere.herokuapp.com/boards.4chan.org/biz/thread/13932651.json")
           .then(res => { //returns a readable stream
                  res.body.getReader().read().then(r => { //returns a Uint8 buffer array
                       var result = new TextDecoder("utf-8").decode(r.value); //Decodes the buffer array into a string
                           console.log(JSON.parse(result)) //the result you want
                   })
            })

it's 2020 now, is there any update? 😃

Can confirm, its 2020 and still no update.
fetch() has the mode: 'no-cors' mode, why axios doesnt just have something similar?

I tried

'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept'

And none of those headers worked. I tried withCredentials on both true and false states, didnt work.

With fetch, it just works.

What am I supposed to do if I dont want to deal with CORS policy and still use axios?
Edit: Plus, why the heck is this issue closed? We obviously still have a problem with this.

You need to define 'Access-Control-Allow-Origin': 'YOUR_IP:YOUR_PORT' in the response headers NOT in the request headers.

Can confirm, its 2020 and still no update.
fetch() has the mode: 'no-cors' mode, why axios doesnt just have something similar?

I tried

'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept'

And none of those headers worked. I tried withCredentials on both true and false states, didnt work.

With fetch, it just works.

What am I supposed to do if I dont want to deal with CORS policy and still use axios?
Edit: Plus, why the heck is this issue closed? We obviously still have a problem with this.

There's no problem with the axios, that's why the issue was closed. just take a chair and read the article on MDN: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

南辕北辙,徒劳无功

Thanks guys, that helped! Pardon me for the inconvenience!

I had this error on axios when I was on my devices mobile hotspot. Then when I used the WiFi at a coffee shop I did not get a CORB

I tried using Wikipedia API and had this same issue.
Adding origin=* to the URL fixed it.

const endpoint = `https://en.wikipedia.org/w/api.php?action=query&origin=*&list=search&srsearch=${searchTerm}&format=json`;

I solved it by not using axios, tried GET from external URLs with $ajax and $get, had no issue with the old jquery stuff. It is a BUG for sure.

it's 2021 now, is there any update? 😃

I'm experiencing a similar "Access-Control-Allow-Headers"-related issue while attempting to hit a zapier webhook from axios (0.18.0) and chrome (75.0.3770.100).

My request is:

axios.post("https://hooks.zapier.com/hooks/catch/xxx/xxxx", { email });

I'll receive an error about the unsupported header:

blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response

image

After reading through this page, my understanding is:

    1. Zapier needs to configure their server response to support Access-Control-Request-Headers for at least "content-type"
    1. I need to configure my request to somehow exclude the "content-type" header-check during the preflight OPT.

Are there any suggestions to achieve option 2? Zapier's common problems about Access-Control-Request-Headers suggests "don't customize the content-type" of your request. However, I don't have any header options in my request, nor any default headers configured to axios, so I can only assume this is implicit on axios' end?


Edit: I'm convinced this has little/nothing to do with axios, but rather poor support on Zapier's end. The request seems to work after switching to a GET with URL params.

Well if in the FAQs they mention not needing any content type params you
could just try the ol
Var xhr = new XMLHTTPRequest() and try it that way without axios.

Is your post to the webhook on the client or the server?

On Tue, Jun 25, 2019, 3:27 PM Pete Schmitz notifications@github.com wrote:

I'm experiencing a similar "Access-Control-Allow-Headers"-related issue
while attempting to hit a zapier webhook from axios (0.18.0) and chrome
(75.0.3770.100).

My request is:

axios.post("https://hooks.zapier.com/hooks/catch/xxx/xxxx", { email });

I'll receive an error about the unsupported header:

blocked by CORS policy: Request header field content-type is not allowed
by Access-Control-Allow-Headers in preflight response

[image: image]
https://user-images.githubusercontent.com/3190970/60138000-9ccdda80-975d-11e9-8f6d-e47bcffe91f1.png

After reading through this page, my understanding is:

-
1. Zapier needs to configure their server response to support
Access-Control-Request-Headers for at least "content-type"
-
1. I need to configure my request to somehow exclude the
"content-type" header-check during the preflight OPT.

Are there any suggestions to achieve option 2? Zapier's common problems
about Access-Control-Request-Headers
https://zapier.com/help/common-problems-webhooks/#posting-json-from-web-browser-access-control-allow-headers-in-preflight-response-error
suggests "don't customize the content-type" of your request. However, I
don't have any header options in my request, nor any default headers
configured to axios, so I can only assume this is implicit on axios' end?


You are receiving this because you commented.
Reply to this email directly, view it on GitHub
https://github.com/axios/axios/issues/853?email_source=notifications&email_token=AHVHGUIDC6DW3YPEKZ2HHZTP4KLWHA5CNFSM4DIVKOX2YY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGODYRYXPA#issuecomment-505646012,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AHVHGUKX32PVCFPCZGRURD3P4KLWHANCNFSM4DIVKOXQ
.

Any news on this? I'm pretty much in the same boat.

@imranimu The problem is a combination of the browser you're using and the server you're making the request to. There's nothing axios can do about it, unless the browser exposes an API that let's it ignore the CORS check.

You have a few options:

If you control the server you're requesting, allow it to respond to all OPTIONS requests with the following headers:

Access-Control-Allow-Origin: https://www.mywebsite.com <<REPLACE WITH YOUR SITE - USE COMMA IF MORE THAN ONE>>
Access-Control-Allow-Methods: GET,PUT,POST,DELETE,OPTIONS
Access-Control-Allow-Headers: Access-Control-Allow-Origin

With express this might look something like this, placed before other routes in your middleware chain:

app.options('/*', (req, res, next) => {
    res.header('Access-Control-Allow-Origin', 'https://www.mywebsite.com');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Access-Control-Allow-Origin');
    res.send(HttpStatusCode.OK);
});

You also have to append a header Access-Control-Allow-Origin: https://www.mywebsite.com' <<replace with your website or list of sites>> to the response.

app.get('/my-cors-friendly-route', async (req, res, next) => {
   const data = await this.http.get('https://www.someothersite.com');
   res.append('Access-Control-Allow-Origin', 'https://www.mywebsite.com');
   res.json(data)
});

Simply put, the browser knows when you're requesting a resource on a different origin (domain), so it sends a preflight check (using the OPTIONS request method type, not GET, POST etc), to see if the server says it's ok to receive the request. It's a basic browser security measure to reduce the chance of a 3rd party website using your API - which you may not want. The code above basically just says that it's ok for a specific website to consume the API. If it can be consumed by all websites, you'd set Access-Control-Origin: *.

Alternatively, if you don't control the server you're making the request to, then expose a route on the server that is serving the page, which makes (proxies) the request for you. This works because the exposed route has the same origin (domain) as your application, so the CORS policy isn't enforced, and the server that you exposed the route isn't a browser, so won't receive a CORS error.

@Aitchy13 the API server i'm connecting to has Access-Control-Origin: *, console gives me this error like in this issue,

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at ‘https://<my_api_host>/Data/Login/’. (Reason: Credential is not supported if the CORS header ‘Access-Control-Allow-Origin’ is ‘*’).

Also you say, to add...

res.header('Access-Control-Allow-Headers', 'Access-Control-Allow-Origin');

... but isn't Access-Control-Allow-Origin only for responses not requests?

Not supported if Access-Control-Allow-Origin : * ... very strange.

Here's some of the API's response headers for some references to help aid future possible solutions:

( This is off a OPTIONS method request before the actual request that gets denied due to CORS )
RESPONSE HEADERS

HTTP/1.1 204 No Content
Date: Fri, 28 Jun 2022 04:08:58 GMT
Server: Apache
X-DNS-Prefetch-Control: off
X-Frame-Options: SAMEORIGIN
Strict-Transport-Security: max-age=15552000; includeSubDomains
X-Download-Options: noopen
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Surrogate-Control: no-store
Cache-Control: no-store, no-cache, must-revalidate, proxy-revalidate
Pragma: no-cache
Expires: 0

Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET,HEAD,PUT,PATCH,POST,DELETE
Access-Control-Allow-Headers: api-key,content-type

Vary: Access-Control-Request-Headers
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive

Or do I have somthing wrong? Was about to snap my laptop in half over this issue.

I had the same problem, after several attempts, testing some solutions, none worked. only after setting the proxy in the package.json.
adds:
"proxy": "api address"
that it will bypass the cors.

@IkarosFeitosa Can you post your config proxy configuration?

@zacharytyhacz you can't send browser credentials when the server responds with Access-Control-Allow-Origin: *.

Either:

  1. change * to be a specific website address.
  2. set ...withCredentials: false in the config/options parameter of the axios request function you're using.
  3. set the proxy property in the config/options parameter of the axios request function you're using, to a valid proxy (example below)
proxy: {
    host: '127.0.0.1',
    port: 9000,
    auth: {
      username: 'mikeymike',
      password: 'rapunz3l'
    }

Any progress? I config my web server to set resposne header, but it seem not work.
image

image
I'm confuse this error tip:
image
CORS should be web browser limit, it need server return allow, i already allow this cors, but then browser told me No 'Access-Control-Allow-Origin' header is present on the requested resource.

I try my server cors config with fetch api, it work well.

If you using nodejs with express. That post might help you.

If you want only some path to be with cors allowed for instance:
/home/fridge - not allowed from other origins
/home/toilet - should be allowed from other origins

You can try the following implementation (worked for me)

In routes/home.js

const express = require('express')
const router  = express.Router()

router.options("/toilet", function(req, res, next){
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
  res.send(200);
});

If you don't use nodejs with express - try googling for OPTIONS method request


Tested from express: 4.16.3

No, :) It is problems when developing(we use http)
when We release on server(we use https)
It doesn't happend.
So just install add on: https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en

app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});

That's solved my life!!

Thank you for the suggestion. I have updated my code to route the request through a proxy:

axios.get('https://a.4cdn.org/a/threads.json', {
  headers: {
    'Access-Control-Allow-Origin': '*',
  },
  proxy: {
    host: '104.236.174.88',
    port: 3128
  }
  }).then(function (response) {
      console.log('response is : ' + response.data);
  }).catch(function (error) {
      if (error.response) {
        console.log(error.response.headers);
      } 
      else if (error.request) {
        console.log(error.request);
      } 
      else {
        console.log(error.message);
      }
  console.log(error.config);
});

However, I'm still getting this error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://a.4cdn.org/a/threads.json. (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘https://boards.4chan.org’).

I have searched through various forums and questions on Stack Overflow and I can't seem to find any solution to this. It would be appreciated if someone could provide some insight.

Hello guys, try this before the axios call, it's worked for me

headers.set('Content-Type', 'application/json')

this was my solution

const key = 'sdmhfkhskdfhkshdkfhsdhfksl';
    const locationUrl = `https://api.fjdsghfjsdghfjgshdjfg`;
    axios.defaults.headers.common['x-api-key'] = key;
    const myresult = await axios.get(locationUrl, { crossdomain: true }).then((result) => {
        return result.data;
    });

I will create a video on how to fix this CORS issue. I will update this comment with a link to my YouTube video.

Edit:
https://youtu.be/hxyp_LkKDdk

it's 2021 now, is there any update? 😃

Yes I'm so much into my shit I really had to check that year shit up 😆

Just use fetch to test if server's cors works first.

And...

axios can request my koa-server, but not iris directly, both of them arms popular cors-middleware.

1358

Why is there no official solution to this problem? I read through this whole thread and am baffled at what seems like a universal problem that no one is really solving in any standard way.

Why is there no official solution to this problem? I read through this whole thread and am baffled at what seems like a universal problem that no one is really solving in any standard way.

The whole CORS issue is not Axios, nor even JavaScript itself. It's a security feature built into most or all browsers. There are ways to 'hack' around it, but it's up to the server to respond with the correct headers.

Why is there no official solution to this problem? I read through this whole thread and am baffled at what seems like a universal problem that no one is really solving in any standard way.

The whole CORS issue is not Axios, nor even JavaScript itself. It's a security feature built into most or all browsers. There are ways to 'hack' around it, but it's up to the server to respond with the correct headers.

So given that response, what's the most "successful" way of implementing a fix for a CORS issue then?

Ok, after two days of research I finally get it.

Speaking strictly, this is not an axios issue. Actually this must not even be considered an issue. axios was designed to work following all that weird and annoying CORS standards, so the message: CORS header ‘Access-Control-Allow-Origin’ missing is expected to happen, thar is the correct working of axios. In the example with the 4chan api, as was said before, the problem is not axios, is the 4chan api itself who is not following the CORS standards.

Some people has suggested the old trick of use a proxy to handle7avoid all that headers validations. Here is a blog from Negar Jamalifard exlaining how to do the trick: https://medium.com/js-dojo/how-to-deal-with-cors-error-on-vue-cli-3-d78c024ce8d3 By the way, I am not sure if this can be considered a bad practice.

In my case I was two days trying to connect to a asp net core api in my own localhost until I realize axios, before sending my get request, automatically was sending a "preflight requests" who is sendign as a OPTIONS method which my server was not prepared to handle. If there is someone who blame is to chrome and firefox for display a message so ambiguous.

Some people has suggested the old trick of use a proxy to handle7avoid all that headers validations. Here is a blog from Negar Jamalifard exlaining how to do the trick: https://medium.com/js-dojo/how-to-deal-with-cors-error-on-vue-cli-3-d78c024ce8d3 By the way, I am not sure if this can be considered a bad practice.

So just proxying is the best possible case for these calls? That's a shame.

So just proxying is the best possible case for these calls? That's a shame.

Well... you also can try to talk with the dude who create the api you are trying to consume and ask them to fix it.

I've solved the problem:
for axios: url= "http://localhost:8080" method='post'
for my Django Server response:
uesrItem = {'user': 'xxx'}
response = JsonResponse(userItem)
response["Access-Control-Allow-Origin"] = "http://localhost:8080"
response["Access-Control-Allow-Credentials"] = 'true'
response["Access-Control-Allow-Methods"] = "POST, OPTIONS"

The problem isnot axios, but the API that you're requesting !

For example I was coded an API in Flask and the GET method was:

@app.route('/api/autores', methods=['GET'])
def get_users():
    drivers_json = []
    for user in user_dao.list_users():
        drivers_json.append(user.to_json())
    return make_response(jsonify(drivers_json), 201)

But the problem was solved when I add a header in API response:

@app.route('/api/autores', methods=['GET'])
def get_users():
    drivers_json = []
    for user in user_dao.list_users():
        drivers_json.append(user.to_json())
    response = jsonify(drivers_json)
    response.headers.add('Access-Control-Allow-Origin', '*')
    return response

Then I log my axios response and I get it:

{data: Array(4), status: 200, statusText: "OK", headers: {…}, config: {…}, …}

I dont know what API you all are using but in Flask It was solved !

In my case there was nothing wrong with axios. I just asked the guy who created the API to enable CORS server-side.

try this

delete axios.defaults.headers.common["X-Requested-With"];

I have used the https://github.com/Rob--W/cors-anywhere workaround and works just fine, but in prod I'll ask the guy who made the api to enable cors for my domain

I don't think you can resolve CORS directly in axios, because CORS is a browser restriction which is between your browser and target servers.

You can either:

  1. Include Access-Control-Allow-Origin in your response headers from your target server.
  2. Do not include hostname in your axios request so it will request your original server. Then from your original server you can do whatever you want to the target server.

Please mention a detailed example code snippet.
It will he helpful.

I was having the same issue on my local.
I added cors on my backend and solved. :)

This is not the issue with the axios This is the issue with the backend. I am using Django. And adding these two will solve the issue.

Add CORS Middlewear

MIDDLEWARE = [
...
'corsheaders.middleware.CorsMiddleware',
...
]

And allowing the CORS.
(Allowing CORS for all)

CORS_ORIGIN_ALLOW_ALL = True

(This is a bit insecure as it allows all origins. Which will make it vulnurable for CSRF attacks)
Hence for production allow only for Specific origins

CORS_ORIGIN_ALLOW_ALL = False

CORS_ORIGIN_WHITELIST = (
    '<YOUR_DOMAIN>[:PORT]',
)

Example :+1:

CORS_ORIGIN_ALLOW_ALL = False

CORS_ORIGIN_WHITELIST = (
    '127.0.0.1:8000',
)

Hi all,
As it has been mentionned, this issue is a browser protection against cross-origin requests. I solved it following these instructions: https://support.google.com/chrome/thread/11089651?hl=en

For those still struggling:
Hopefully by now you understand that this isn't an issue with Axios and the browser is blocking CORS because of a header not being set by the server. If you do understand this and are still having trouble with your own server not setting the headers be sure to set it on your actual web server when using a reverse proxy. For instance, many Node/Express apps are served by NGINX in production with a reverse proxy. See enable-cors.org for how to set it in NGINX.

For those still struggling:
Hopefully by now you understand that this isn't an issue with Axios and the browser is blocking CORS because of a header not being set by the server. If you do understand this and are still having trouble with your own server not setting the headers be sure to set it on your actual web server when using a reverse proxy. For instance, many Node/Express apps are served by NGINX in production with a reverse proxy. See enable-cors.org for how to set it in NGINX.

I have been struggle 3 hours, nothing change on client side, finally I added the following stuff on server:

install egg-cors ( for egg project only)

// ./config/config.default.js

config.cors = {
    origin: ["http://localhost:8080"],
    allowedHeaders: [
      "Content-Type",
      "Authorization",
      "Access-Control-Allow-Methods",
      "Access-Control-Request-Headers"
    ],
    credentials: true,
    enablePreflight: true
  };

that's all

const board = this.props.routeParams.tag;
axios.get('https://cors-anywhere.herokuapp.com/' + 'https://a.4cdn.org/' + board + '/threads.json', config)
.then(function (response) {
console.log(response.data);
});

Just use fetch to test if server's cors works first.

And...

axios can request my koa-server, but not iris directly, both of them arms popular cors-middleware.

1358

This worked for me and need to learn why

I was Working with Tornado and Vuejs, axios was not the problem, on my backend aded:

# Tornado
class ClassName(tornado.web.RequestHandler):
    def set_default_headers(self):
        self.set_header("Content-Type", "application/json")
        self.set_header("Access-Control-Allow-Origin", "*")
        self.set_header("Access-Control-Allow-Headers", "content-type")
        self.set_header(
            'Access-Control-Allow-Methods',
            'POST, GET, OPTIONS, PATCH, PUT'
        )

@robertjchristian
It's Worked
Verrrrrrrrrrry Thanks

I am having the same issue
My Code
axios({
method: "get",
url: "http://localhost:4000/users",
})
.then(response => {
console.log(response);
})
.catch(Error => {
console.log(Error)
});
}
Getting this error
Access to XMLHttpRequest at 'http://localhost:4000/users' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Could anyone give me step by step solution to what I should do ?

@albertpinto First of all you should understand that axios is not the problem, the "backend" that you are using need be able to receive external data. so in google you can search. something like _enable cors on (put the language or framework that are you using)_

@albertpinto look at all the possible solutions in this mega thread. It's not a client-side/front-end issue on your end - it is in fact the server (localhost:4000). The server needs to respond with CORS headers to allow the origin.

For example, your server should reply with headers such as:

Access-Control-Allow-Origin:  *
Access-Control-Allow-Headers: Content-Type

I solved this by the following :

  1. Install cors npm : npm install cors (on your rest node server in my case http://localhost:4000)

This also goes on your end point:
var cors = require('cors')
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())

Thanks for all the suggestions!

// For CORS, if you use express js, you can simply use cors package via npm.

app.use(
    cors({
        credentials: true,
        origin: [
            'http://localhost:8080',
            'http://your-production-website.com'
        ]
    }),
)

cURL does not enforce CORS rules. Those rules are enforced by browsers for security purposes.

When you mention that you added the relevant header, I assume you mean you added those headers to the request. Actually, the header is expected in the response headers from the server, indicating that the resource is allowed to be accessed by other websites directly.

FYI, CORS - Cross Origin Resource Sharing. Since your API does not support it, you have two options -

  1. Use a proxy server on the same domain as your webpage to access 4chan's API or,
  2. Use a proxy server on any other domain, but modify the response to include the necessary headers.

I'd like to vote to close this issue as "Not an issue".

@sunnykgupta
same logic, same body, but angular http post request to remote backend endpoint does not receive CORS block error

If you're having a Go server running, suggest you to use Gorilla

headersOk := handlers.AllowedHeaders([]string{"X-Requested-With", "Content-Type"})
originsOk := handlers.AllowedOrigins([]string{"*"})
methodsOk := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "OPTIONS"})

err := http.ListenAndServe("localhost:8081", handlers.CORS(originsOk, headersOk, methodsOk)(r))

I solved this by the following :

1.create a vue.config.js file in the root of the project right beside package.json, containing:

module.exports = {
    devServer:{
        proxy: {
            '/apiv1': {
                target: 'https://fuping.site/',
                changeOrigin: true,
                pathRewrite: {
                    '^/apiv1': ''
                }
            },
        },
    }
}

2.make a http request like this:

this.$axios({
          method:'get',
          url:'apiv1/about/',

        }).then(function(response){
          console.log(response.data)
        }).catch(error=>{
          console.log(error)
        })

axios.get('https://a.4cdn.org/a/threads.json', {
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
},
proxy: {
host: '104.236.174.88',
port: 3128
}
}).then(function (response) {
console.log('response is : ' + response.data);
}).catch(function (error) {
if (error.response) {
console.log(error.response.headers);
}
else if (error.request) {
console.log(error.request);
}
else {
console.log(error.message);
}
console.log(error.config);
});

Hello everyone,
I am just posting this as it took hours for me to solve this.

First of all, CORS is definitely a server-side problem and not client-side but I was more than sure that server code was correct in my case since other apps were working using the same server on different domains. The problem started when I started using axios with my custom instance.

In my case, it was a very specific problem when we use a baseURL in axios instance and then try to make GET or POST calls from anywhere, axios adds a slash / between baseURL and request URL. This makes sense too, but it was the hidden problem. My Laravel server was redirecting to remove the trailing slash which was causing this problem.

In general, the pre-flight OPTIONS request doesn't like redirects. If your server is redirecting with 301 status code, it might be cached at different levels. So, definitely check for that and avoid it.

I hope this might help someone although none of it is a bug.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ghprod picture ghprod  ·  3Comments

9tor picture 9tor  ·  3Comments

reggi picture reggi  ·  3Comments

helmus picture helmus  ·  3Comments

c0debreaker picture c0debreaker  ·  3Comments