我的 node.js 后端在埠 5000 上運行,我的反應客戶端在埠 3000 (http://localhost:3000) 上運行。react客戶端在package.json代理中有如下url:http://localhost:5000(后端url)
我曾經在 baseurl http://localhost:3000 使用 axios 從客戶端向后端發出 api 請求。代理執行了它的功能,cors 沒有問題。
在 app.js 的后端有以下代碼塊:
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000')
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE')
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type, Authorization')
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true)
// Pass to next layer of middleware
next()
})
現在我決定將我的網站移動到 VPS 服務器。我在那里安裝了 nginx,這就是我在 location 塊的 /etc/nginx/sites-available/default 中寫的。
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
proxy_pass http://localhost:3000; #whatever port your app runs on
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
使用 pm2 我運行我的 node.js 后端并回應客戶端。它們在與以前相同的埠上運行。
例如,我的服務器現在可以在 my-site.com 上使用。當您轉到該網址時,它會打開我的客戶端。到目前為止,一切都按預期進行。但是,當我的客戶訪問我的后端時,我收到如下錯誤:
GET http://127.0.0.1:3000/api/categories net::ERR_CONNECTION_REFUSED
你能告訴我如何修復它并讓我的 api 請求被執行嗎?
uj5u.com熱心網友回復:
你的 React 代理可能沒有在 VPS 上運行。無論哪種方式,最好使用 Nginx,因為 React 代理僅用于開發用途。
您可以配置 Nginx 以將請求轉發/api到 Node.js 應用程式的路徑,就像為 React 應用程式配置根路徑一樣。
location /api {
proxy_pass http://localhost:5000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/455167.html
上一篇:Javascript中的innerHTML和console.log的區別
下一篇:來自守護行程的Docker-compose錯誤回應:nginx的清單:1.15-alphine未找到:清單未知:清單未知
