使用 Express/Node.js 从 Mongo 数据库获取数据时出现 404 错误

Getting 404 error while fetching data from Mongo DB using Express/Node.js

我无法理解我收到的这个 404 错误。这是我第一次尝试使用 Mongo 数据库和 Node.js 所以原谅我,还没有习惯路由。我只是想向 localhost:3000/users 发出 GET 请求,并将基本文本呈现到显示“users”的页面,以便我可以测试路由。我还没有制作任何类型的模型或模式。当我进入该页面时,我收到一条包含以下内容的消息:Cannot GET /users.

我相信我的 app.js 文件设置正确并且应用程序已连接到 Mongo 数据库。

这是我的 app.js 文件 - 路线在底部:

const express = require('express')
const dotenv = require('dotenv')
const connectDB = require('./config/db')

// Instantiate Morgan - this logs requests to the terminal (similar to rails)
const morgan = require('morgan')

// Load config.env file
dotenv.config({ path: './config/config.env' })

// initialize app with express 
const app = express()


// run Connect DB to connect to your host 
connectDB()

// if environment = development, run request logs
if (process.env.NODE_ENV === 'development') {
    app.use(morgan('dev'))
}

// We may deploy to heroku - so we need to set the env variable 
const PORT = process.env.PORT || 5000
app.listen(PORT, console.log(`Server running in ${process.env.NODE_ENV} mode on port ${PORT}`))


// Routes
app.use('/users', require('./routes/users'))

这是我的 users.js 路径文件夹中的文件:

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

// Routes 
// @route GET /users -> gets all users in the database

router.get('/users', (req, response) => {
    response.send('Users')
})


module.exports = router

另外 - 这是我的 config.env 文件。我通过 Mongo 数据库托管在 AWS 服务器上。

PORT = 3000 
MONGO_URI = mongodb+srv://Ricky:<redacted>@readr.s99uq.mongodb.net/readr?retryWrites=true&w=majority

关于我在这里可能出错的地方有什么想法吗?我相信我已经正确设置了路线,但可能在某处搞砸了。

试试 localhost:3000/users/users 因为 /users 指向你的 users.js 文件中的所有路由,并且你有 /users 所以它是嵌套的。所以如果你想在你的 users.js 文件中得到 localhost:3000/users 的结果,将路由更改为 / 而不是 /users

PS/ 此外,如果那是您在配置文件中的真实用户名和密码,请将其删除。