首页 > 解决方案 > 无法设置简单的 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 终端中收到消息。

还有几次我设法 REG 在 VSC 终端中收到消息。

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

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

请在下面找到我的代码。
服务器.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

包.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"
  }
}

任何人为什么会这样?

先感谢您!

标签: node.jsroutesauthorization

解决方案


你试过 http://localhost:5000/login 吗?我没有看到代码中定义的路径的“/ auth”部分。与“http://localhost:5000/”相同,您的代码中没有为该路径提供资源。

据我所知,这些是唯一可行的途径。

  • http://localhost:5000/登录
  • http://localhost:5000/注册

我还注意到您的入口点文件名是 server.js。也许您需要更新您的 package.json 以反映这一点而不是“index.js”?


推荐阅读