Trying to separate api and web route:
route/index.js
var api = function () {
router.get('/:id', function (req, res, next) {
...
});
return router;
}
var web = function () {
router.get('/:id', function (req, res, next) {
...
});
return router;
}
module.exports = {
api: api,
web: web
};
app.js
var indexAPI = require('./app/routes/accounts').api;
var indexWeb = require('./app/routes/accounts').web;
app.use('/api/index', indexAPI);
but it didn't route successfully.
I have change it to and it is working:
var api = (function () {
router.get('/:id', function (req, res, next) {
...
});
return router;
})();
var web = (function () {
router.get('/:id', function (req, res, next) {
...
});
return router;
})();
module.exports = {
api: api,
web: web
};
Related
How to implement middleware like this in socket.io? Please help
EXPRESS APP
var myLogger = function (req, res, next) {
console.log('LOGGED')
next()
}
app.use(myLogger)
app.get('/', function (req, res) {
res.send('Hello World!')
})
SOCKET APP (I am using express pattern but its not working)
var myLogger = function (data,next) {
console.log('DOING DATA VALIDATION...')
next()
}
io.use(myLogger)
io.on('someEvent/', function (data, callback) {
callback('Hello World!')
})
Error : next() is not define!
app.use(function (req, res, next) {
req.io = io;
next();
});
This assigns a socket object to every request.
If somebody's still wondering.
To use middleware on all sockets:
io.use((socket, next) => {
// isValid is just a dummy function
if (isValid(socket.request)) {
next();
} else {
next(new Error("invalid"));
}
});
This example is from the official docs of socket.io
To use a middleware for a specific client:
io.on('connection', async (client) => {
client.use((socket, next) => {
console.log(`got event: ${socket[0]} in client middleware, moving on with next() just like in express`)
next()
});
// rest of your code
newConnection(client)
})
I have a node.js app that uses express, handlebars and passport.js for authentication. I have setup a routes folder for login
app.js
app.use('/login', require('./routes/login'));
routes/ login.js
const checkAuthenticated = (req, res, next) => {
if (req.isAuthenticated()) {
return res.redirect("/");
}
next();
};
router.get("/", checkAuthenticated, (req, res) => {
res.render("login");
});
module.exports = router;
This works fine.
However, if I put the checkAuthenticated middleware function in app.js then export and require it in login.js I get this error.
router.get() requires callback
app.js
app.use('/login', require('./routes/login.js'));
const checkAuthenticated = (req, res, next) => {
if (req.isAuthenticated()) {
return res.redirect("/");
}
next();
};
module.exports = { checkAuthenticated };
routes/login.js
const { checkAuthenticated } = require('../app.js');
router.get("/", checkAuthenticated, (req, res) => {
res.render("login");
});
module.exports = router;
Why doesn't it work when this function is required from another file like a normal function? I am trying to avoid duplication as I need exact same function for routes/register.js
Here is the example:
var app = require('express')();
function validateToken(req, res, next) {
// Do something with request here
next();
};
app.get('/user/login', function(req, res) {
//code
});
app.post('/user/register', function(req, res) {
//code
})
app.put('/user/register', validateToken, function(req, res) {
//code
})
app.delete('/user/delete', validateToken, function(req, res) {
//code
})
If I have 10 api that need validToken, I should add validToken middleware 10 times, like:
app.method('......', validateToken, function(req, res) {
//code
})
app.method('......', validateToken, function(req, res) {
//code
})
....
app.method('......', validateToken, function(req, res) {
//code
})
app.method('......', validateToken, function(req, res) {
//code
})
How can I group api by using the same middleware?
Here's how to re-use the same callback function for multiple routes (like middleware):
var app = require('express')();
function validateToken(req, res, next) {
// Do something with request here
next();
};
app.get('/user/login', function(req, res) {
// code
});
app.post('/user/register', function(req, res) {
// code
});
// Be sure to specify the 'next' object when using more than one callback function.
app.put('/user/register', validateToken, function(req, res, next) {
// code
next();
});
app.delete('/user/delete', validateToken, function(req, res, next) {
// code
next();
});
Also, you can replace app.METHOD (e.g. .post, .get, .put, etc.) with app.all and your callback will be executed for any request type.
Just wrong, so do not put into mass participation of the (Google translated from: 刚才看错了,改成这样就不用放进传参了)
var group = {url:true,url:true,url:true};
app.use(function(req,res,next){
if(group[req.url]){
// Do something with request here
next();
} else {
next();
}
})
When I use http://tes.com/routes, it will route to the api=>get('/'), instead of web=>get('/'). Why?
app.js:
var api = require('./app/routes/routes').api;
var transaction_web = require('./app/routes/routes').web;
app.use('/api/routes', transaction_api);
app.use('/routes', transaction_web);
routes.js:
var api = (function () {
router.get('/', function (req, res, next) {
...
});
return router;
})();
var web = (function () {
router.get('/', function (req, res, next) {
...
});
return router;
})();
module.exports = {
api: api,
web: web
};
The reason is because that's the order in which you're adding the routes.
This:
var api = (function () {
router.get('/', function (req, res, next) {
...
});
return router;
})();
is the same as:
router.get('/', function (req, res, next) {
...
});
var api = router;
The same thing happens with the other block where you assign web, so you end up with:
router.get('/', function (req, res, next) {
// api route
});
var api = router;
router.get('/', function (req, res, next) {
// web route
});
var web = router;
The solution would be to create separate Router instances. For example:
var api = new express.Router();
api.get('/', function (req, res, next) {
// web route
});
var web = new express.Router();
web.get('/', function (req, res, next) {
// web route
});
When I make GET http://localhost:8080/messages/3/sentiments for the code below why param method is called two times? So If I have 10 routes it will be called 10 times?
var comments = new Router();
comments.get('/comments', function (req, res, next) {
res.send('Comments by message_id=' + req.message._id);
})
var sentiments = new Router();
sentiments.get('/sentiments', function (req, res, next) {
res.send('Comments by message_id=' + req.message._id);
})
var messages = new Router();
messages.param('_message', function (req, res, next, _id) {
console.log("Set message");
fs.readFile(__filename, function () {
req.message = { _id: _id };
next();
});
})
messages.use('/messages/:_message/', comments);
messages.use('/messages/:_message/', sentiments);
app.use(messages);
app.listen(8080);
Confirmed to be a bug in Express < 4.3
https://github.com/visionmedia/express/issues/2121