[英]nodejs Route.get() requires callback functions but got a [object String]
I'm starting coding using nodejs with express. 我开始使用带有express的nodejs进行编码。 So i did this in my file test.js which is into my folder routes :
所以我在我的文件test.js中做到了这一点,它位于我的文件夹路由中:
const express = require('express');
const router = new express.Router();
router.get('/test', (req, res) => {
res.send(`I'm a test`);
});
module.exports = router;
Then, in my server.js : 然后,在我的server.js中:
const test = require('./server/routes/test');
app.use('/test', test);
In my browser, it tells me Cannot get/test 在我的浏览器中,它告诉我无法获取/测试
I don't understand why. 我不明白为什么。 Need for help.
需要帮助。 Thanks
谢谢
The problems seems to be how you are mounting the router. 问题似乎出在您如何安装路由器。 Looking the the router middleware API it seems you should be doing it like this.
查看路由器中间件API ,看来您应该这样做。
test.js test.js
const express = require('express');
const router = new express.Router();
router.get('/test', (req, res, next) => {
res.send("I'm a test");
next();
});
module.exports = router;
server.js server.js
const express = require('express');
const app = express();
const test = require('./test');
app.use('/', test);
app.listen(3000);
in order to access /test
use router.get('/'
and app.use('/test'
because express will concatenate /
and /test
. 为了访问
/test
使用router.get('/'
和app.use('/test'
因为express将连接/
和/test
。
in your case you have to access /test/test
so do this and enter /test
in your borwser: 在您的情况下,您必须访问
/test/test
因此请在浏览器中输入/test
:
const express = require('express');
const router = new express.Router();
router.get('/', (req, res) => { res.send("I'm a test"); });
module.exports = router;
Then, in your server.js : 然后,在您的server.js中:
const test = require('./server/routes/test'); app.use('/test', test);
Simple fix that should resolve your issue. 简单的修复程序应该可以解决您的问题。
Replace 更换
const router = new express.Router();
With 同
const router = express.Router();
在res.send()
添加"I'm a test"
,我的意思是在该String周围添加"
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.