javascript - 我的路线已定义,但快递返回 404 错误
问题描述
我已经检查了这里的每一个副本,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,
},
});
};
有人能帮忙吗?
先感谢您
解决方案
我正在访问类似 localhost:5000/signup 的路线
但是您的路由器有router.route('/signup')
并且路由器安装在app.use('/signup', userRouter);
这使得路径/signup/signup
不是/signup
。
/
路由器中没有安装,/signup
因此找不到 URL。
推荐阅读
- mysql - 我在 nodejs 中的 mysql 查询有什么问题?
- mips - 您如何在 PCspim MIPS 汇编语言上正确输出字符串元音和非元音和?
- r - 运行 dev.off() 时在 R 中收到错误
- javascript - this.setState 在 this.setState 的回调中没有设置状态
- angular - 离子 - 如何一次将数据添加到 sqlite 数据库表?
- protractor - 如何在 CodeCeptjs 中调用 customhelper?
- java - 无法解决 2.0:缺少需求 [2.0] osgi.wiring.package;(osgi.wiring.package=org.apache.poi.xssf.usermodel)
- android - 应该返回 LiveData 的房间查询总是返回 NULL
- ios - 为customView设置背景颜色没有效果
- macos - 在 MacOS 上,如何跟踪哪些页面已加载到内存中?