Enable CORS in my React App with Node.js backend

后端 未结 3 796
借酒劲吻你
借酒劲吻你 2021-01-05 14:17

I used create-react-app to build my react app. This app does a POST call on another API (elasticsearch), hosted on a different server (not owned/managed by me). So once the

相关标签:
3条回答
  • 2021-01-05 14:32

    Add below code in node js API

      app.use(function(req, res, next) {
         res.header("Access-Control-Allow-Origin", "*");
         res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
         next();
    });
    

    or

    //allow OPTIONS on all resources
    app.options('*', cors())
    
    0 讨论(0)
  • 2021-01-05 14:38

    You need to set up a proxy server for API requests - https://create-react-app.dev/docs/proxying-api-requests-in-development/

    I do not fully understand the details for Elastic server, but you can put the Express code into src/server.js file, inspired by https://stackoverflow.com/a/20539239/1176601:

    var express = require('express')
    var request = require('request')
    var cors = require('cors')
    var app = express()
    
    app.use(cors())
    
    app.use('/', function(req, res) {
      var url = 'https://' +
        req.get('host').replace('localhost:80', 'servername.domain:11121') + 
        req.url
      req.pipe(request({ qs:req.query, uri: url })).pipe(res);
    })
    
    app.listen(80, function () {
      console.log('CORS-enabled web server listening on port 80')
    })
    

    update package.json

    "scripts": {
       ...
       "server": "node src/server.js"
    },
    "proxy": "http://localhost:80"
    

    Modify your client:

    let client = new elasticsearch.Client({
        host: "{cred.user}:{cred.pass}@@localhost:80",
        log: "trace",
    });
    

    And start it by npm run server (before or after npm start, e.g. in a separate terminal).

    Before the first start, you will need to install all required modules, npm i -D express request cors.

    0 讨论(0)
  • 2021-01-05 14:52

    You should add that to the file where you configure the server you are using. If you were using express you would add that to the server.js file you are talking about but it seems you have an elasticsearch server and a react app so you do not have a node.js backend.

    You probably will have to include a cors configuration in the elasticsearch server.

    0 讨论(0)
提交回复
热议问题