使用Node.js后端在我的React App中启用CORS [英] Enable CORS in my React App with Node.js backend

查看:128
本文介绍了使用Node.js后端在我的React App中启用CORS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用create-react-app构建了我的react应用。这个应用程式在另一个API(elasticsearch)上执行POST呼叫,该API托管在其他伺服器上(非我拥有/管理)。因此,一旦用户以表格形式输入数据,onSubmit就基本上会调用进行调用的getResponse()方法。
初始化客户端:

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查询:

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);
            }
        });
    }

但是我收到的CORS错误如下:

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

在阅读了关于同一问题的文章之后,我发现使用cors npm模块可以解决此问题(至少在开发中)。但是我不明白该在哪里放置这段代码:

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')
})

我的问题如下:
1.在上面的哪里添加此代码?在我的应用程序的app.js中?如果是,请给我一个例子。我使用的是这样的东西:

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. 如果此代码是添加到其他文件,然后哪个文件?是server.js吗?如果是,我在哪里可以找到?我使用的是Windows7。Node安装在客户目录中:C:\MYSW\NodeJs\12.1.0。我在这里看到一些server.js:C:\Users\user1\Scratch\node\myreact_ui\node_modules\react-dom\server.js,但这是正确的文件

  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:\MYSW\NodeJs\12.1.0. I see some server.js in here: C:\Users\user1\Scratch\node\myreact_ui\node_modules\react-dom\server.js, but is it the right file

请给我一个示例,说明如何添加代码以及文件中的确切位置。我是React和Node的新手,所以我对内部知识不太了解。我被困在这里已经好几天了,真的需要一些帮助。谢谢。

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.

推荐答案

您需要为API请求设置代理服务器- https://create-react-app.dev/docs/proxying-api-requests-in- development /

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

我不完全了解Elastic server的详细信息,但是您可以将Express代码放入 src / server中。 js 文件,灵感来自 https://stackoverflow.com/a/20539239/1176601

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')
})

更新package.json

update package.json

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

修改客户:

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

然后通过 npm run server (在 npm开始之前或之后,例如在另一个终端中。

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

在第一次开始之前,您需要安装所有 require d个模块, npm i -D表达请求的详细信息

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

这篇关于使用Node.js后端在我的React App中启用CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆