NodeJS 在EC2示例上从我部署的IP地址站点请求时面临CORS策略问题

iibxawm4  于 2023-08-04  发布在  Node.js
关注(0)|答案(1)|浏览(87)

我已经使用nginx在AWS EC2示例上部署了一个全栈React/Node应用程序,并面临CORS策略问题,我已经在代码中解决了这个问题
x1c 0d1x的数据
Index.js

const express = require('express');
const cors = require('cors');
require('dotenv').config();

const app = express()
const port = process.env.PORT || 5000;

// midleware to use API Endpoints
const corsOptions = {
  origin: 'http://13.200.107.25'
}
app.use(express.json());
app.use(cors(corsOptions));

// Serving client react app build 
const path = require('path');
const _dirname = path.dirname("");
const buildPath = path.join(_dirname , "../client/build");

app.use(express.static(buildPath));

app.get('/*', (req, res) => {
  res.sendFile(
    path.join(__dirname, "../client/build/index.html"),
    (err) => {
      if(err)
      {
        res.status(500).send(err);
      }
    }
  )
})

//Available Routes
app.use('/api/auth', require('./Routes/authRoute'));
// app.use('/api/notes', require('./Routes/notes'))

app.listen(port, () => {
  console.log(`iNotebook listening at http://localhost:${port}`)
})

字符串
我使用pm2启动后端服务器,它也为我的react应用程序的../client/build提供服务



我已经更改了/etc/nginx/sites-available/default文件的配置

server {
   listen 80 default_server;
   listen [::]:80 default_server;
    
   server_name _;
   
   location / {
        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;
    }
}


我已经重新启动了pm2和nginx,并使用sudo nginx -t测试了nginx语法配置,结果成功
我在index.js中给出了corsOptions作为参数

// midleware to use API Endpoints
const corsOptions = {
  origin: 'http://13.200.107.25'
}
app.use(express.json());
app.use(cors(corsOptions));

wkftcu5l

wkftcu5l1#

我觉得你们的配置还可以。
一个很好的方法来了解你的头是否正常,就是在bash终端中使用curl

curl http://13.200.107.25 -I

字符串
此命令显示您网站的标题:

HTTP/1.1 200 OK
Server: nginx/1.18.0 (Ubuntu)
Date: Tue, 01 Aug 2023 15:56:25 GMT
Content-Type: text/html; charset=UTF-8
Content-Length: 1457
Connection: keep-alive
X-Powered-By: Express
Access-Control-Allow-Origin: http://13.200.107.25 #<---- CORS
Vary: Origin
Accept-Ranges: bytes
Cache-Control: public, max-age=0
Last-Modified: Tue, 01 Aug 2023 14:11:19 GMT
ETag: W/"5b1-189b1705fac"


正如你所看到的,Cors头是可以的。
问题是你的前端试图连接到http://localhost:5000,这很令人困惑,因为你说你的后端(节点)在同一个EC2中(而不是在localhost中)。
如果你的后端运行在同一个EC2示例中,解决方案会为**http://13.200.107.25更改react项目中的每个http://localhost:5000**请求。在这种情况下,CORS报头是不必要的,因为请求来自同一个源。
如果实际上,你的后端运行在你的个人电脑(localhost)你必须配置cors(在你的后端)与http://localhost...并根据您的浏览器配置它,以允许像在这个问题CORS error on request to localhost dev server from remote site这样的请求。因为从已经托管在互联网上的网站获取localhost是不安全的。

相关问题