問題描述
我使用 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模板網!