如何修复Node express错误:cannot GET



我试图为一个应用程序创建一个简单的后端api,我正在工作(create-react-app),并决定使用节点express。当我打开浏览器时,我得到错误'cannot GET',我不明白为什么。

这是我的server/index.js文件:
const express = require("express");
const PORT = process.env.PORT || 3001;
const app = express();
app.get("/api", (req, res) => {
res.json({ message: "Hello from server!" });
});

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

这是我的开始脚本:

"scripts": {
"start": "node index.js"
}

在我的控制台中,我看到这个错误:

Failed to load resource: the server responded with a status of 404 (Not Found)
这是我的文件夹结构:我有一个名为1REPMAX的应用程序它包含文件夹
>build
>node-modules
>public
>server
>node_modules
>index.js
>package-lock.json
>package.json
>src
.gitignore
package-locj.json
package.json

我所做的就是进入服务器,然后运行npm start.

当我打开浏览器到localhost:3001时,我得到了错误。你能告诉我哪里做错了吗?如果需要更多的信息,请告诉我。另外,当我第一次运行npm start时,它启动得很好,但现在每次我运行它,我都会得到这个错误:

code: 'EADDRINUSE',
errno: -48,
syscall: 'listen',
address: '::',
port: 3001

我不知道这是否有关系。

第一个错误是因为你的应用程序不监听/路径,只监听/api路径。

第二个错误是由server/index.js文件中重复的app.listen()调用引起的。

为了解决这个问题,你的代码应该看起来像这样:
const express = require("express");
const PORT = process.env.PORT || 3001;
const app = express();
app.get("/", (req, res) => res.send("Main page")); 
app.get("/api", (req, res) => {
res.json({ message: "Hello from server!" });
});

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

最新更新