繁体   English   中英

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

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

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

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

这是我的 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 DB 在 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/另外,如果那是您在配置文件中的真实用户名和密码,请将其删除。

暂无
暂无

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

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