Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Getting 'Cross-Origin Request Blocked' on a GET request #853

Closed
adl1995 opened this issue Apr 23, 2017 · 143 comments
Closed

Getting 'Cross-Origin Request Blocked' on a GET request #853

adl1995 opened this issue Apr 23, 2017 · 143 comments

Comments

@adl1995
Copy link

adl1995 commented Apr 23, 2017

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
@sunnykgupta
Copy link

sunnykgupta commented Apr 23, 2017

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

@adl1995
Copy link
Author

adl1995 commented May 30, 2017

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.

@JoseTavares
Copy link

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

@ramziddin
Copy link

ramziddin commented Jul 23, 2017

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

@priyankachiluveri
Copy link

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

@yassinmziya
Copy link

saaaaame

@PetitBateau
Copy link

PetitBateau commented Aug 9, 2017

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

@adl1995
Copy link
Author

adl1995 commented Aug 10, 2017

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

@PetitBateau
Copy link

PetitBateau commented Aug 10, 2017

@adl1995 It did the trick for me ;)

@ramziddin
Copy link

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.

@PetitBateau
Copy link

PetitBateau commented Aug 11, 2017

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

@ronnin
Copy link

ronnin commented Aug 17, 2017

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

@adl1995
Copy link
Author

adl1995 commented Aug 20, 2017

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

@steelow
Copy link

steelow commented Aug 21, 2017

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.

@seungha-kim
Copy link

Read this, everyone.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

@swyxio
Copy link

swyxio commented Sep 23, 2017

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?

@jigz
Copy link

jigz commented Nov 1, 2017

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.

@mbmohib
Copy link

mbmohib commented Nov 3, 2017

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

@jigz
Copy link

jigz commented Nov 3, 2017

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

@robertjchristian
Copy link

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.

@steveswork
Copy link

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

@AdnanCukur
Copy link

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

@fadilnatakusumah
Copy link

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

@challenger532
Copy link

it's 2018 now, is there any update?

@shafikhaan
Copy link

@challenger532 Nope Still not.

@chrisalcantara
Copy link

chrisalcantara commented Jan 24, 2018

The error is still prevalent.

My advice: use a different library.

@LeonardoBonetti
Copy link

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 !

@kalpetros
Copy link

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

@superern
Copy link

superern commented Nov 15, 2019

try this

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

@portothree
Copy link

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

@ethanyoung
Copy link

ethanyoung commented Dec 6, 2019

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.

@definoob
Copy link

definoob commented Dec 6, 2019

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

@definoob
Copy link

definoob commented Dec 6, 2019

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

@dheerajmpai
Copy link

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

@thomasgauvin
Copy link

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

@dutgriff
Copy link

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.

@WillieOng-HK
Copy link

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

@myoneflag
Copy link

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

@lokesh14v
Copy link

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

@ivancarrancho
Copy link

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

@mahdipakravan-dev
Copy link

@robertjchristian
It's Worked
Verrrrrrrrrrry Thanks

@albertpinto
Copy link

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 ?

@ivancarrancho
Copy link

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

@zacharytyhacz
Copy link

@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

@albertpinto
Copy link

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!

@naywin-programmer
Copy link

naywin-programmer commented Apr 12, 2020

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

@geyuqiu
Copy link

geyuqiu commented Apr 17, 2020

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

@anirudhmurali
Copy link

anirudhmurali commented Apr 18, 2020

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

@fupinglee
Copy link

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

@oudream
Copy link

oudream commented Apr 25, 2020

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

@cybersupernova
Copy link

cybersupernova commented May 3, 2020

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.

@axios axios locked and limited conversation to collaborators May 3, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests