简体   繁体   English

Express 服务器在 EC2 上没有响应

[英]Express Server not responding on EC2

I have hosted an Express server on EC2.我在 EC2 上托管了一个 Express 服务器。 The server at http://xx.xxx.xxx.xxx:3000 is accessible from any browser as well as Postman. But on making requests to the server from my React Frontend, I get a 404 error.位于http://xx.xxx.xxx.xxx:3000的服务器可从任何浏览器以及 Postman 访问。但是在从我的 React 前端向服务器发出请求时,我收到 404 错误。 How to resolve?如何解决? I have already allowed cross-origin requests to my node server with the following code.我已经允许使用以下代码对我的节点服务器进行跨源请求。

const cors = require('cors')
app.use(cors())

The same express server when running on my localhost responds perfectly fine to the request received from the React Frontend.在我的本地主机上运行时,同一个快速服务器对从 React 前端收到的请求做出完美响应。

Edit: full server code added below.编辑:下面添加了完整的服务器代码。

const express = require('express')
const fs = require('fs')
const cors = require('cors')
const app = express()

app.use(cors())
app.use(express.urlencoded({ extended: false }))
app.use(express.json())

app.get('/', (req, res) => {
    var sendSomething = "error"
    res.send(sendSomething)
})
   
app.listen(3001, () => {
    console.log('Server runs on port 3001')
})

Make sure your code is having the minimum structure as below:确保您的代码具有如下所示的最小结构:

 const express = require('express') const cors = require('cors'); const bodyParser = require('body-parser') const http = require('http'); const app = express() app.use(cors()); app.use(express.urlencoded({ extended: false })); app.use(express.json()); app.get('/', (req, res) => { res.send("<html><div style='text-align:center;margin-top:20%'><h1>Welcome to My Page </h1></div></html>"); }); const httpServer = http.createServer(app); httpServer.listen(env.port, () => { console.log(`API is now live on ${env.port}`); });

If yes then go to AWS console, services->vpc->security->security groups-> click on a security group id and make sure in the inbound rules source is '0.0.0./0'.如果是,则 go 到 AWS 控制台,services->vpc->security->security groups-> 单击安全组 id 并确保入站规则源为“0.0.0./0”。 (this means access is open for all ips. make sure to restrict this later.) (这意味着所有 ip 都可以访问。请确保稍后对其进行限制。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM