【问题标题】:Getting 404 error while fetching data from Mongo DB using Express/Node.js使用 Express/Node.js 从 Mongo DB 获取数据时出现 404 错误
【发布时间】:2020-11-20 13:50:30
【问题描述】:

我无法确定收到的这个 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

关于我可能在哪里出错的任何想法?我相信我已经正确设置了路线,但可能在某个地方搞砸了。

【问题讨论】:

    标签: node.js mongodb express http-status-code-404


    【解决方案1】:

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

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

    【讨论】:

    • 非常感谢!在我的其余设置中工作就像一个魅力和很高兴知道。我在配置中修改了密码 - 很好看。
    猜你喜欢
    • 2021-08-24
    • 2021-12-20
    • 1970-01-01
    • 2023-01-09
    • 1970-01-01
    • 2017-09-14
    • 2017-11-29
    • 1970-01-01
    • 2019-02-25
    相关资源
    最近更新 更多