Enable CORS from front-end in React with axios?

坚强是说给别人听的谎言 提交于 2020-05-27 04:57:48

问题


I am using React on the front-end and I'm calling API from another domain which I don't own. My axios request:

axios(requestURL, {
        method: 'GET',
        headers: {
            'Access-Control-Allow-Origin': '*',
            'Content-Type': 'application/json',
            'Authorization': key,
            withCredentials: true,
            mode: 'no-cors',
          }

I keep on getting the same error: CORS header ‘Access-Control-Allow-Origin’ missing. Is this something I can overcome from the frontend? I know for a fact that people use that API so it can't be backend fault, right? I tried requesting a lot of APIs and not even one worked with my code. I tried using https://cors-anywhere.herokuapp.com and it worked fine for like a week, I think its down today. I want my site to stay 24/7 so using a proxy is not an option


回答1:


You will, unfortunately, need to proxy the request somehow. CORS requests will be blocked by the browser for security reasons. To avoid this, backend needs to inject allow origin header for you.

Solutions depend on where you need to proxy, dev or production.

Development environment or node.js production webserver

The easiest way to do it in this scenario is to use the 'http-proxy-middleware' npm package

const proxy = require('http-proxy-middleware');

module.exports = function (app) {
    app.use(proxy('/api', {
        target: 'http://www.api.com',
        logLevel: 'debug',
        changeOrigin: true
    }));
};

Production - Web server where you have full access Check the following page to see how to enable such proxying on your webserver:

https://enable-cors.org/server.html

Production - Static hosting / Web server without full access

If your hosting supports PHP, you can add a php script like: https://github.com/softius/php-cross-domain-proxy

Then hit a request from your app to the script, which will forward it and inject headers on the response

If your hosting doesn't support PHP Unfortunately, you will need to rely on a solution like the one that you have used.

In order to avoid relying on a third party service, you should deploy a proxy script somewhere that you will use.

My suggestions are:

  • Move to a hosting that supports php :) (Netlify could be a solution, but I'm not sure)

  • You can deploy a node.js based proxy script of your own to Firebase for example (firebase functions), to ensure it will not magically go down, and the free plan could possibly handle your amount of requests.

  • Create a free Amazon AWS account, where you will get the smallest instance for free for a year, and run an ubuntu server with nginx proxy there.




回答2:


You should allow CORS from back-end for making requests.



来源:https://stackoverflow.com/questions/55200786/enable-cors-from-front-end-in-react-with-axios

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