无法设置简单的Node.js服务器



我对Node.js和整个后端都是新手。我试图建立简单的node.js服务器来创建授权(管理员,用户)我想没什么特别的。当我尝试使用localhost:5000在浏览器中输入我的服务器时我得到这个错误。

localhost/:1 GET http://localhost:5000/ 404 (Not Found)

使用http://localhost:5000/auth/login或任何其他路由时也是如此。奇怪的是,在同一时间,我总是收到消息server started on port 5000在VSC终端。

也有几次我设法得到消息VSC终端REG

router.get('/registration', async () => {
console.log('REG')
})

但在浏览器控制台我得到相同的错误Failed to load resource: the server responded with a status of 404 (Not Found)


server.js
const express = require('express');
const mongoose = require('mongoose');
const authRouter = require('./authRouter')//yes
const PORT = process.env.PORT || 5000;
const connectionString = 'mongodb+srv://Ivan:aldaron1@cluster0.fivve.mongodb.net/usersBD?retryWrites=true&w=majority'//yes
const app = express();
app.use(express.json());
app.use(authRouter);
const start = async () => {
try {
await mongoose.connect(connectionString)
app.listen(PORT, () => console.log(`server started on port ${PORT}`))
} catch (error) {
console.log(error)
}
}
start()

authController.js

class authController {
async registration(req, res) {
try {
res.json("server works")
console.log(" 123 ")
} catch (e) { }
}
async login(req, res) {
try {
res.json("server works")
console.log(" 123 ")
} catch (e) { }
}
async getUsers(req, res) {
try {
res.json("server works")
console.log(" 123 ")
} catch (e) { }
}
}
module.exports = new authController();

authRouter.js

const Router = require('express')
const router = new Router()
//const controller = require('./authController')

router.get('/registration', async () => {
console.log('REG')
})
router.get('/login', async () => {
console.log('REG')
})
//router.post('/login',)
//router.get('/users', controller.getUsers)
module.exports = router

package.json

{
"name": "node-server-ivan",
"version": "1.0.0",
"description": "my first node.js server",
"main": "index.js",
"scripts": {
"test": "echo "Error: no test specified" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1",
"mongodb": "^3.6.3",
"mongoose": "^5.11.15",
"node": "^15.8.0"
},
"devDependencies": {
"nodemon": "^2.0.7"
}
}

你知道为什么会这样吗?

提前感谢!

您试过http://localhost:5000/login吗?我没有看到&;/auth&;在代码中定义的路径的一部分。"http://localhost:5000/"您的代码中没有为该路径提供资源。

在我看来,这是唯一可行的路径。

  • http://localhost: 5000/登录
  • http://localhost: 5000/登记

我也注意到你的入口点文件名是server.js。也许你需要更新你的软件包。Json来反映这个,而不是"index.js"?

最新更新