且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在componentDidMount内部具有HTTP授权标头的API请求

更新时间:2022-05-20 05:36:51

此错误是跨域错误.

Web浏览器在处理AJAX请求时遇到了麻烦:它们必须寻址到相同的来源或由第三方本身授权,否则将被阻止.由于您无法控制Yelp,因此建议您采取一种解决方法.

Web browsers have a catch with AJAX requests: They need to be addressed to the same origin or be authorized by the third-party itself, otherwise they are blocked. Since you have no control over Yelp, I suggest you take a workaround.

可用的解决方法

  • 您使用的是 jsonp 之类的东西.此方法主要包括在<script>标记中发出请求.服务器会将响应包装在Javascript脚本中,然后将其加载到页面中. ( https://en.wikipedia.org/wiki/JSONP ).服务器必须提供这种格式才能使该解决方法正常工作.
  • 您使用反向代理.您可以将NodeJS设置为一个.在此设置中,您将向您的来源发出 yelp 请求,该请求会将其重定向到yelp服务器.之所以可行,是因为您的Node代理与您的浏览器没有相同的限制. (例如: https://github.com/nodejitsu/node-http-proxy )
  • You use something like jsonp. This method basically consists in making the request in a <script> tag. The server will wrap the response inside a Javascript script and it will be loaded unto the page. (https://en.wikipedia.org/wiki/JSONP). The server MUST offer this format for that workaround to work.
  • You use a reverse proxy. You can set NodeJS to act as one. In this setup, you will make your yelp request to your origin who will redirect it to the yelp server. This works because your Node proxy does not have the same limitations as your browser. (ex: https://github.com/nodejitsu/node-http-proxy)

也许还有其他方法可以解决这个问题,但是那些是流行的方法.

There may be other ways to get around this, but those are popular methods.

希望这会有所帮助.