基本快递设置:不向本地端口发送任何东西

Basic express setup: not sending anything to local port

我创建了一个前端应用程序,现在正尝试将后端合并到其中。 在同一个前端应用程序中,我在根目录中添加了一个 index.js 文件,并在 index.js 文件中安装了 express 和 require 它。

非常基本的设置如下:

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

const port = process.env.PORT || 3001

const app = express()

app.get('/', (req, res) => {
  res.send({
    greetings: 'hi'
  })
})

app.listen(port, () => {console.log(`Server on port ${port}`)})

根据我的终端,服务器在端口 3001 上成功运行,但是,在 localhost:3001 上,我没有看到我在 app.get 中设置的任何 json 响应。 它说 Cannot GET / 相反。当我在 devtool(Network) 中检查时,它显示 404.

这似乎是一个非常简单的设置,但这里可能出了什么问题?

我刚刚明白为什么。我安装了 nodemon,但我的“启动”脚本是“node index.js”。应该使用“nodemon index.js” 现在使用 nodemon index.ks

你的代码很好,没有错误,我测试了它,它按预期工作。

但是有几点需要注意,除非需要,否则请将后端保持在单独的状态 folder/dirctory。

回到你的问题,有很多可能性,比如某些模块没有正确安装

尝试运行以下命令

//this will install if any library is currupt or not installed properly
npm i

如果不行就试试clearing cache

还要记住,在 nodeJS 开发服务器中不会​​自动刷新更改,您需要重新启动服务器才能看到更改,或者您可以使用名为 Nodemon 的开发依赖项(这将在保存更改时自动重启服务器)