from origin 'xxx' has been blocked by CORS policy: [duplicate]

牧云@^-^@ 提交于 2019-12-20 07:47:17

问题


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.



来源:https://stackoverflow.com/questions/55037494/from-origin-xxx-has-been-blocked-by-cors-policy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!