Enable CORS from front-end in React with axios?

前端 未结 3 1167
花落未央
花落未央 2021-02-14 10:19

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\',
           


        
3条回答
  •  不思量自难忘°
    2021-02-14 10:38

    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.

提交回复
热议问题