我的路线似乎不存在,但我不明白为什么

问题描述 投票:0回答:1

对于网络开发来说相当陌生,所以这很可能是我的一个简单错误,但在过去的一个小时里我一直在尝试解决这个问题,但我一无所获。

这是我当前的代码,在我将其精简到最低限度后,仍然无法工作。

app.js:

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

const port = process.env.PORT || 3000;
const apiPath = process.env.API_PATH || '/api/v1';

const gamesRoute = require('./routes/gamesRoute');

const app = express();

app.use(cors());
app.use(express.json());

app.use(`${apiPath}/games`, gamesRoute);

// Start server, binding it to specified port
app.listen(port, function() {
    // Log a message when server is successfully started
    console.log(`Server is running on port ${port}`);
});

app.get('/', function(req, res) {
    res.send("test");
});

gamesRoute.js:

const express = require('express');
const router = express.Router();

router.get('/', async function(req, res) {
    console.log("test");
    res.json({ msg: "test" });
});

module.exports = router;

响应(我正在使用 VSCode 扩展“humao.rest-client”,并调用

GET localhost:3000/api/v1/games
):

HTTP/1.1 404 Not Found
X-Powered-By: Express
Access-Control-Allow-Origin: *
Content-Security-Policy: default-src 'none'
X-Content-Type-Options: nosniff
Content-Type: text/html; charset=utf-8
Content-Length: 151
Date: Wed, 10 Jan 2024 11:46:35 GMT
Connection: close

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /api/v1/games</pre>
</body>
</html>

我在控制台中也什么也没得到。 我的假设是我犯了一个非常基本的错误,但我不知道它是什么。

我尝试查看 YouTube 上的教程、快速文档和随机帖子。根据我的发现,我做的事情是正确的,所以我有点陷入困境。我还浏览了超过一半的堆栈溢出建议的问题,这些问题可能是重复的,但它们似乎都不能解决我的问题,除非我太笨了,无法理解它。

javascript node.js express routes
1个回答
-1
投票

如果你想在 gamesRoute 文件中使用 router.use('/') ,那么 const router =express.Router() 是有效的,但你需要使用路由,而不是在这里使用与 atteched 代码相同的路由。

gamesRoute.js:

const express = require('express');
const router = express();

router.get('/', async function(req, res) {
    console.log("test");
    res.json({ msg: "test" });
});

module.exports = router;
© www.soinside.com 2019 - 2024. All rights reserved.