【发布时间】: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