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 · 64 comments

Comments

Projects
None yet
@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

This comment has been minimized.

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

This comment has been minimized.

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

This comment has been minimized.

Copy link

JoseTavares commented Jul 17, 2017

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

@ramziddin

This comment has been minimized.

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

This comment has been minimized.

Copy link

priyankachiluveri commented Aug 3, 2017

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

@yassinmziya

This comment has been minimized.

Copy link

yassinmziya commented Aug 6, 2017

saaaaame

@PetitBateau

This comment has been minimized.

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

This comment has been minimized.

Copy link
Author

adl1995 commented Aug 10, 2017

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

@PetitBateau

This comment has been minimized.

Copy link

PetitBateau commented Aug 10, 2017

@adl1995 It did the trick for me ;)

@ramziddin

This comment has been minimized.

Copy link

ramziddin commented Aug 11, 2017

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

This comment has been minimized.

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

This comment has been minimized.

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

This comment has been minimized.

Copy link
Author

adl1995 commented Aug 20, 2017

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

@steelow

This comment has been minimized.

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

This comment has been minimized.

Copy link

seungha-kim commented Sep 2, 2017

@sw-yx

This comment has been minimized.

Copy link

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

@JigzPalillo

This comment has been minimized.

Copy link

JigzPalillo 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

This comment has been minimized.

Copy link

mbmohib commented Nov 3, 2017

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

@JigzPalillo

This comment has been minimized.

Copy link

JigzPalillo 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

This comment has been minimized.

Copy link

robertjchristian commented Dec 13, 2017

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

This comment has been minimized.

Copy link

steveswork commented Dec 14, 2017

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

This comment has been minimized.

Copy link

AdnanCukur commented Dec 16, 2017

@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

This comment has been minimized.

Copy link

fadilnatakusumah commented Dec 22, 2017

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

@challenger532

This comment has been minimized.

Copy link

challenger532 commented Jan 24, 2018

it's 2018 now, is there any update?

@shafikhaan

This comment has been minimized.

Copy link

shafikhaan commented Jan 24, 2018

@challenger532 Nope Still not.

@chrisalcantara

This comment has been minimized.

Copy link

chrisalcantara commented Jan 24, 2018

The error is still prevalent.

My advice: use a different library.

@ComputerCarl

This comment has been minimized.

Copy link

ComputerCarl commented Jul 8, 2018

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.

@mddanishyusuf

This comment has been minimized.

Copy link

mddanishyusuf commented Jul 26, 2018

I think this header config will solve this issue.

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

Thanks

@letorruella

This comment has been minimized.

Copy link

letorruella commented Aug 2, 2018

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

@AousAnwar

This comment has been minimized.

Copy link

AousAnwar commented Aug 7, 2018

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.

@yasincidem

This comment has been minimized.

Copy link

yasincidem commented Aug 14, 2018

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

This comment has been minimized.

Copy link

ScottyFillups commented Aug 20, 2018

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 😄

@chabgood

This comment has been minimized.

Copy link

chabgood commented Sep 30, 2018

crossdomain: true

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

@murilobd

This comment has been minimized.

Copy link

murilobd commented Oct 2, 2018

secure

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

@bunday

This comment has been minimized.

Copy link

bunday commented Oct 3, 2018

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

@harisbaig100

This comment has been minimized.

Copy link

harisbaig100 commented Oct 6, 2018

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.

@heyjoy21

This comment has been minimized.

Copy link

heyjoy21 commented Oct 13, 2018

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

@sunlee-newyork

This comment has been minimized.

Copy link

sunlee-newyork commented Oct 17, 2018

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.

@ibnclaudius

This comment has been minimized.

Copy link

ibnclaudius commented Oct 23, 2018

@mddanishyusuf Solution worked for me.

I think this header config will solve this issue.

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

Thanks

Thanks! ;)

@Historia2

This comment has been minimized.

Copy link

Historia2 commented Oct 28, 2018

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

@odahcam

This comment has been minimized.

Copy link

odahcam commented Nov 12, 2018

#853 (comment) worked with fetch API and a .NET 4.5 web API.

@LvDevR1

This comment has been minimized.

Copy link

LvDevR1 commented Nov 21, 2018

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

@fernandoruch

This comment has been minimized.

Copy link

fernandoruch commented Nov 30, 2018

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

This comment has been minimized.

Copy link

sahgoku commented Dec 13, 2018

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

@eladonline

This comment has been minimized.

Copy link

eladonline commented Dec 14, 2018

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

This comment has been minimized.

Copy link

Ethan0007 commented Dec 18, 2018

Hi,

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

Thanks.

@serafss2

This comment has been minimized.

Copy link

serafss2 commented Dec 23, 2018

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.

@tantana5

This comment has been minimized.

Copy link

tantana5 commented Dec 28, 2018

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

@adj-dev

This comment has been minimized.

Copy link

adj-dev commented Jan 8, 2019

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.

@maxgfr

This comment has been minimized.

Copy link

maxgfr commented Jan 16, 2019

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

@atherdon atherdon referenced this issue Feb 8, 2019

Open

Bug #29

@anilpai

This comment has been minimized.

Copy link

anilpai commented Feb 13, 2019

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.

@AlanGreyjoy

This comment has been minimized.

Copy link

AlanGreyjoy commented Feb 19, 2019

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

@Bizzle-Dapp

This comment has been minimized.

Copy link

Bizzle-Dapp commented Feb 22, 2019

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment