我使用 create-react-app 来构建我的 react 应用程序.这个应用程序在另一个 API(elasticsearch)上进行 POST 调用,托管在不同的服务器上(不是我拥有/管理的).因此,一旦用户在表单中输入数据,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
在阅读了关于相同问题的 SO 后,我发现使用 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())
或
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;
如果要将此代码添加到其他文件中,那么是哪个文件?是 server.js 吗?如果是,我在哪里可以找到这个?我使用的是 Windows 7.节点安装在客户目录中:C:MYSWNodeJs12.1.0.我在这里看到了一些 server.js:C:Usersuser1Scratch odemyreact_ui ode_modules eact-domserver.js,但它是正确的文件
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
请给我一个示例,说明如何添加代码以及在文件中的确切位置.我是 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 服务器的详细信息,但您可以将 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 start
之前或之后,例如在单独的终端中).
And start it by npm run server
(before or after npm start
, e.g. in a separate terminal).
在第一次开始之前,你需要安装所有 require
d 模块,npm i -D express request cors
.
Before the first start, you will need to install all require
d modules, npm i -D express request cors
.
这篇关于使用 Node.js 后端在我的 React 应用程序中启用 CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!