No Access-Control-Allow-Origin error in Meteor app

社会主义新天地 提交于 2019-12-23 15:52:22

问题


I added CORS extension to chrome. When called ajax from localhost I got response in the form of XML. If I disabled CORS extension I got the following error. I referred so many questions in this community. But I cant't resolve my problem. It may duplicate but I'm asking this question for help with hope.

XMLHttpRequest cannot load https://buzz.machaao.com/feed. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 401..

And my code is

HTTP.get('https://buzz.machaao.com/feed',{
   headers: {
      "Access-Control-Allow-Origin" : "*"
      }
        }, (err, res) => {
      if(err) {
            console.log(err);
      }
      else {
            console.log(res);
      }
    });

回答1:


The https://buzz.machaao.com/feed site doesn’t send the Access-Control-Allow-Origin response header, so you need to make your request through a proxy instead—like this:

var proxyUrl = 'https://cors-anywhere.herokuapp.com/',
    targetUrl = 'http://catfacts-api.appspot.com/api/facts?number=99'

HTTP.get(proxyUrl + targetUrl,
  (err, res) => {
    if(err) {
      console.log(err);
    }
    else {
      console.log(res);
    }
});

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS explains why browsers won’t let you access the response cross-origin from frontend JavaScript code running in a web app unless the response includes an Access-Control-Allow-Origin response header.

https://buzz.machaao.com/feed has no Access-Control-Allow-Origin response header, so there’s no way your frontend code can access the response cross-origin.

Your browser can get the response fine and you can even see it in browser devtools—but your browser won’t expose it to your code unless it has a Access-Control-Allow-Origin response header. So you must instead use a proxy to get it.

The proxy makes the request to that site, gets the response, adds the Access-Control-Allow-Origin response header and any other CORS headers needed, then passes that back to your requesting code. And that response with the Access-Control-Allow-Origin header added is what the browser sees, so the browser lets your frontend code actually access the response.



来源:https://stackoverflow.com/questions/43277435/no-access-control-allow-origin-error-in-meteor-app

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