Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

javascript - Enable CORS in my React App with Node.js backend

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 user enters the data in the form, onSubmit basically calls getResponse() method that makes the call. Initialize client:

let client = new elasticsearch.Client({
    host: "https://{cred.user}:{cred.pass}@@servername.domain:11121",
    log: "trace",
});

API query:

getResponse?=?()?=>?{
????????client
??????????.search({
????????????index:?'custom_index_1',
????????????body:?{
????????????????query:?{
????????????????????match:?{"data":?this.state.data}
????????????????},
????????????}
????????},function(error,?response,?status)?{
????????????if?(error)?{
????????????????const?errorMessage=?{error};
????????????????console.log(errorMessage);
????????????}
????????????else?{
????????????????this.setState({results:?response.hits.hits});
????????????????console.log(this.state.results);
????????????}
????????});
????}

But I'm getting the CORS error as follows:

Failed to load resource: the server responded with a status of 403 (Forbidden)
localhost/:1 Access to XMLHttpRequest at 'https://servername.domain:11121/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.console.js:40 
WARNING: 2019-11-21T07:54:32Z No living connections

After reading in SO about the same issue, I found that using the cors npm module can fix this issue (at least in development). But I do not understand where do I put this code:

var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())

OR

var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())

app.get('/products/:id', function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for all origins!'})
})

app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})

My questions are as follows: 1. Where do I add this code above? in my react app's app.js? If yes, can someone give me an example please. I am using something like this:

import statements
class App extends Component {
 <code>
}
export default App;
  1. If this code is to be added to some other file then which file? Is it server.js? If yes, where do I find this? I'm using Windows 7. Node is installed in a customer directory: C:MYSWNodeJs12.1.0. I see some server.js in here: C:Usersuser1Scratch odemyreact_ui ode_modules eact-domserver.js, but is it the right file

  2. Please give me a sample of how the code is added and where exactly in the file. I am new to React and Node so I do not know much about the internals. I'v been stuck here for days now and really need some help. Thanks.

Everywhere it says, add this code and it work, no one mentions where do I add it and how? Any help appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...