from origin 'xxx' has been blocked by CORS

2020-05-09 18:09发布

问题:

I'm trying the most basic get request from the browser and it fails due to CORs issues.

axios.get(
  "https://github.com/login/oauth/authorize?client_id={ID}"
);

Is it just not possible to make this request from the browser? I'm trying to understand how it's possible to click a button and have this link work.

from origin 'http://localhost:3001' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

回答1:

Simple answer is NO.

You can't call any endpoint (different origin) without server's permission.

ok! I got it. But why? How it works ?

It's called CORS (Cross-Origin Resource Sharing). In one line, it is a browser security . Browser blocks you to prevent such request.

Ok! but how browers knows that I don't have the permission or I'm cheating. :D

Well, if you check Network Tab of a browser, browser sends one more request to server (before actual request) with OPTION method. In the response of the request, server tells to browers if it's valid request or not.

For more details, Read MDN https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS



回答2:

Ideal Solution

Your server should enable the cross origin requests and not the client. To do this, you can check this cool link with implementations and configurations for multiple platforms

Front-end fix to try

var config = {
    headers: {'Access-Control-Allow-Origin': '*'}
};

axios.get(
    "https://github.com/login/oauth/authorize?client_id={ID}, config"
);

Quick Temporary fix for development

Add this chrome extension to your chrome browser and turn it on. There won't be any cors issue but it is not a permanent fix.