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

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

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Reactions: 111
  • Comments: 143

Commits related to this issue

Most upvoted comments

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

Any news on this? I’m pretty much in the same boat…

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 …

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

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.

it’s 2018 now, is there any update?

The error is still prevalent.

My advice: use a different library.

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

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.

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

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

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

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"]);

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”.

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.

@adl1995 It did the trick for me 😉

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

I think this header config will solve this issue.

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

Thanks

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.

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

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

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

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

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

@mddanishyusuf Solution worked for me.

I think this header config will solve this issue.

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

Thanks

Thanks! 😉

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

Extraordinary it works !!!

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

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

南辕北辙,徒劳无功

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

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

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.

saaaaame

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

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.

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

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

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)

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

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

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 !

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.

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

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

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.

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.

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

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

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.

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.

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

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

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

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

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 <module>/config/index.js. I prefered to modify this one since referenced in <module>/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

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.

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 👍

CORS_ORIGIN_ALLOW_ALL = False

CORS_ORIGIN_WHITELIST = (
    '127.0.0.1:8000',
)

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 😆

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.

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

  2. 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

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

  4. talk to your server-side dev mate

Hope it’s helpful

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', {})

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.

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

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.

will help only you, but how about other people?

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

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

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

@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

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

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

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

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.

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.

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