首页 > 解决方案 > 我的路线已定义,但快递返回 404 错误

问题描述

我已经检查了这里的每一个副本,StackOverflow但没有一个能解决问题......

这是我在用于创建服务器的文件之后运行应用程序时库查找app.js的第一个文件。expressserver.js

您可以查看代码中的注释以更好地理解问题


// Implement cors
app.use(cors());

app.use(bodyParser.json());

app.use('/', viewRouter); // This route works
app.use('/signup', userRouter); // This route doesn't work
app.use('/test', userRouter); // This route doesn't work
module.exports = app;


这是我的userRouter.js

const express = require('express');
const router = express.Router();

const authController = require('../controllers/authController');

// See below for the code snippet for these two functions

router.route('/signup').get(authController.test); // When I visit this route it gives back a 404;

router.post('/signup', authController.signup); // When I visit this route it gives back a 404;


router.get('/test', (req, res) => { // When I visit this route it gives back a 404;
  res.send('Hello, World!');
});

console.log('Express can run me'); // I can get this log on my terminal which means the file is run but I can't get the routes to above to work!

module.exports = router;

这是authController.js具有我的两个功能的代码


const User = require('../models/userModel');

exports.signup = async (req, res, next) => {
  try {
    // Get the data from req.body and add it to the database;
    const user = await User.create(req.body);

    res.status(201).json({
      status: 'success',
      data: {
        user,
      },
    });
  } catch (err) {
    res.status(400).json({
      status: 'fail',
      message: err,
    });
  }
};

exports.test = (req, res, next) => {
  console.log('Inside the test function'); // Doesn't get logged to the terminal!

  const test = 'This is the test data';
  res.status(201).json({
    status: 'success',
    data: {
      test,
    },
  });
};


有人能帮忙吗?

先感谢您

标签: javascriptnode.jsexpress

解决方案


我正在访问类似 localhost:5000/signup 的路线

但是您的路由器有router.route('/signup')并且路由器安装在app.use('/signup', userRouter);这使得路径/signup/signup不是/signup

/路由器中没有安装,/signup因此找不到 URL。


推荐阅读