Enable CORS in my React App with Node.js backend

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.


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())