How to allow CORS in react.js?

后端 未结 8 1570
[愿得一人]
[愿得一人] 2020-12-25 12:11

I\'m using Reactjs and using API through AJAX in javascript. How can we resolve this issue? Previously I used CORS tools, but now I need to enable CORS.

相关标签:
8条回答
  • 2020-12-25 12:43

    on the server side in node.js I just added this and it worked. reactjs front end on my local machine can access api backend hosted on azure:

    // Enables CORS
    const cors = require('cors');
    app.use(cors({ origin: true }));
    
    0 讨论(0)
  • 2020-12-25 12:44

    there are 6 ways to do this in React,

    number 1 and 2 and 3 are the best:

    1-config CORS in the Server-Side

    2-set headers manually like this:

    resonse_object.header("Access-Control-Allow-Origin", "*");
    resonse_object.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    

    3-config NGINX for proxy_pass which is explained here.

    4-bypass the Cross-Origin-Policy with chrom extension(only for development and not recommended !)

    5-bypass the cross-origin-policy with URL bellow(only for development)

    "https://cors-anywhere.herokuapp.com/{type_your_url_here}"
    

    6-use proxy in your package.json file:(only for development)

    if this is your API: http://45.456.200.5:7000/api/profile/

    add this part in your package.json file: "proxy": "http://45.456.200.5:7000/",

    and then make your request with the next parts of the api:

    React.useEffect(() => {
        axios
            .get('api/profile/')
            .then(function (response) {
                console.log(response);
            })
            .catch(function (error) {
                console.log(error);
            });
    });
    
    0 讨论(0)
提交回复
热议问题