I'm new to Node.js. I've pulled some code from examples, but somehow I've broken something :).
At this time, in my app.js file, I have a line that I think wires up Express with Node.js. That line looks like this:
app.js
var routes = require('./routes/index');
// ...
app.get('/', routes.router);
Then, in ./routes/index.js I have the following:
routes/index.js
var express = require('express');
var router = express.Router();
/* GET home page */
router.get('/', function(req, res) {
res.send('respond with a resource');
});
module.exports = router;
When I run this, I get the following error:
Error: Route.get() requires callback functions but got a [object Undefined]
at Route.(anonymous function) [as get]
I don't understand. What am I doing wrong?
Thanks!
app.js
var routes = require('./routes/index');
//var routes = require('./routes') --> this works
// ...
app.use('/', routes); //Using the router instance as a middleware , relative to '/'
routes/index.js
var express = require('express');
var router = express.Router(); // new instance of Router
/* GET home page */
router.get('/', function(req, res) {
res.send('respond with a resource');
});
module.exports = router; // You export the intance
UPDATE if you want more than 1 route file
app.js
var routes = require('./routes')
app
.use("/user",routes.user)
.use("/other",routes.other)
routes/index.js
module.exports = {
user : require(./user),
other : require(./other)
}
routes/user.js
var router = require("express").Router()
router.get("/",function (req,res){
// GET /user
})
.post("/",function (req,res){
//POST /user
})
module.exports = router;
routes/other.js
var router = require("express").Router()
router.get("/",function (req,res){
// GET /other
})
.post("/",function (req,res){
//POST /other
})
module.exports = router;
An example of a basic server.js:
var express = require('express');
var app = express();
app.get('/', function(req, res) {
res.sendfile(__dirname + '/client/views/index.html');
});
app.listen(3000, function() {
console.log('Server running on localhost:3000');
});
Comparing, I believe you need to listen to the port. Also I think your res.send should be sending an actual file.
More documentation on Nodejs here: https://nodejs.org/api/
Also found a related questions on SO: Node Route.get() requires callback function but got a [object undefined]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.