Enable CORS in my React App with Node.js backend

后端 未结 3 794
借酒劲吻你
借酒劲吻你 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: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.

提交回复
热议问题