Мои маршруты определены, но express возвращает ошибку 404 - PullRequest
0 голосов
/ 02 августа 2020

Я проверил все дубликаты здесь на StackOverflow, но ни один из них не решил проблему ...

Вот мой app.js первый файл, который библиотека express ищет при запуске приложения после мой server.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,
    },
  });
};


Может ли кто-нибудь помочь с этим?

Заранее спасибо

1 Ответ

2 голосов
/ 02 августа 2020

Я посещаю такие маршруты, как этот localhost: 5000 / signup

Но ваш маршрутизатор имеет router.route('/signup'), а маршрутизатор установлен на app.use('/signup', userRouter);, что делает путь /signup/signup не /signup.

В маршрутизаторе, подключенном к /signup, нет /, поэтому URL-адрес не найден.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...