In a practice example, i'm trying to create a restfull API, very simple. The plain GET and POST methods works well, but the GET, PUT and DELETE method pointing to /api/bears/:bear_id just stay there, waiting...
// CONFIGURACION INICIAL //
// ===================== //
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var db = mongoose.connection;
// CONFIGURANDO APP //
// ================ //
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
mongoose.connect('mongodb://localhost:27017/bears');
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function cb () {
console.log('conexion establecida');
})
var Bear = require('./models/bear_model.js');
var port = process.env.PORT || 8080; // seteo del puerto
var router = express.Router(); // instancia del ruteador
Above, the simple config, below, the snippet that is causing me problems:
router.use(function (req, res, next) { // simple logger
if (req.method === 'GET')
console.log('executing query on id %s', JSON.stringify(req.params));
else if (req.method === 'PUT')
console.log('executing query on id %s', JSON.stringify(req.params));
else
console.log('executing query on id %s', JSON.stringify(req.params));
});
router.route('/bears/:bear_id')
.get(function (req, res) {
Bear.findById(req.params.bear_id, function (err, bear) {
if (err)
res.send(err);
res.json(bear);
});
}) // end GET /bears/:bear_id
.put(function (req, res) {
Bear.findById(req.params.bear_id, function (err, bear) {
if (err)
res.send(err)
bear.name = req.body.name; // Update bear_id of Bear
bear.save(function (err) {
if (err)
res.send(err);
res.json({msg: 'Bear actualizado!'});
});
});
}) // end PUT /bears/:bear_id
.delete(function (req, res) {
Bear.remove({
_id: req.params.bear_id
}, function (err, bear) {
if (err)
res.send(err);
res.json({ msg: 'Bear eliminado' });
});
}); // end DELETE /bears/:id && router /bears/:id
app.use('/api', router); // la api usará como base el prefijo /api
Executing one route with a param log me: executing query on {}, so, the req.params.bear_id simply is not captured, and if i change req.params by req.params.bears_id, obviously i get an undefined log, so i read de docs and think i'm doing generally well the process but don't catch the issue.
You are not calling next() in your logger, so you're never getting to your router, which results in no response.
router.use(function (req, res, next) { // simple logger
if (req.method === 'GET')
console.log('executing query on id %s', JSON.stringify(req.params));
else if (req.method === 'PUT')
console.log('executing query on id %s', JSON.stringify(req.params));
else
console.log('executing query on id %s', JSON.stringify(req.params));
next();
});
Now the reason you are not seeing params in your logger is because params are only visible if the route definition has params. Your logger middleware doesn't define a specific route, therefore there are no params. A solution to this would be to use Router.param
router.param('bear_id', function(req, res, next, bear_id) {
if (req.method === 'GET')
console.log('executing query on id ' + bear_id);
else if (req.method === 'PUT')
console.log('executing query on id ' + bear_id);
else
console.log('executing query on id ' + bear_id);
next();
});
More simply:
router.param('bear_id', function(req, res, next, bear_id) {
console.log(req.method + ' with id ' + bear_id);
next();
});
This works this way by design, you can find more information on github:
https://github.com/strongloop/express/issues/2088
Related
I have a Express server resolving GET /companies/:id/populate/. Now, I would like to setup GET /companies/populate/ (without the :id). However, I can't make this route to work. If I try, for example, GET /companies/all/populate/, it works, so it seems the pattern for an Express route is path/:key/path/:key.
Is this true? Thanks!
Edit: Adding code.
server.js
'use strict';
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var cors = require('cors');
var mongoUri = 'mongodb://localhost:27017';
mongoose.connect(mongoUri);
var db = mongoose.connection;
db.on('error', function() {
throw new Error('Unable to connect to database at' + mongoUri);
});
// runs Express
var app = express();
// uses Cors
app.use(cors());
// uses bodyParser
app.use(bodyParser.json());
// requires Mongo models
require('./models');
// includes routes.js, passing the object 'app'
require('./routes')(app);
// listens for connections on port 3000
app.listen(3000, function() {
console.log("Express started on Port 3000");
});
routes.js
module.exports = function(app) {
// thumbs up if everything is working
app.get('/', function(req, res, next) {
res.send('👍');
console.log('Server Running');
res.end();
});
// companies
var companies = require('./controllers/companies');
app.get('/companies', companies.findAll);
app.get('/companies/:id', companies.findById);
app.get('/companies/:id/populate', companies.populate);
app.get('/companies/populate', companies.populateAll);
app.post('/companies', companies.add);
app.patch('/companies/:id', companies.patch);
app.delete('/companies/:id', companies.delete);
};
/controllers/companies.js
var mongoose = require('mongoose');
Company = mongoose.model('Company');
// GET /companies
// status: works, needs error handling
exports.findAll = function(req, res) {
Company.find({}, function(err, results) {
return res.send(results);
});
};
// GET /companies/:id
// status: works, needs to check error handling
exports.findById = function(req, res) {
var id = req.params.id;
Company.findById(id, function(err, results) {
if (results) res.send(results);
else res.send(204);
});
};
// POST /companies
// status: works, needs error handling
exports.add = function(req, res) {
Company.create(req.body, function(err, results) {
if (err) {
return console.log(err)
} else {
console.log('company created');
}
return res.send(results);
});
};
// PATCH /companies/:id
// status: works, needs error handling
exports.patch = function(req, res) {
var id = req.params.id;
var data = req.body;
Company.update( { '_id' : id }, data, function(err, numAffected) {
if (err) return console.log(err);
return res.send(200);
});
};
// DELETE /companies/:id
// status: works, needs error handling, make sure that we are sending a 204 error on delete
exports.delete = function(req, res) {
var id = req.params.id;
Company.remove({ '_id': id }, function(results) {
console.log('deleted ' + id); // tester
return res.send(results);
});
};
// GET /companies/:id/populate
exports.populate = function(req, res) {
var id = req.params.id;
Company
.findOne({ _id: id })
.populate('contacts country')
.exec(function (err, results) {
if (err) return handleError(err);
else res.send(results);
});
};
// GET /companies/populate
exports.populateAll = function(req, res) {
Company
.find({})
.populate('contacts country')
.exec(function (err, results) {
if (err) return handleError(err);
else res.send(results);
});
};
I wrote some code for login authentication using express. I used express-session. Code sample is
// Authentication and Authorization Middleware
var auth = function(req, res, next) {
if (req.session && req.session.admin) {
return next();
} else {
console.log("failed");
return res.sendStatus(401);
}
}
// Login endpoint
router.post('/login', function (req, res) {
var collection = db.get("login");
collection.find({}, function(err, details) {
if (!req.body.username || !req.body.password) {
res.send('login failed');
} else if(req.body.username === details[0].name && req.body.password === details[0].password ) {
req.session.admin = true;
var data = {
"status": "success",
"message": "login success!"
}
res.send(data);
} else {
var data = {
"status": "failure",
"message": "login failed"
}
res.send(data);
}
});
});
// Logout endpoint
router.get('/logout', auth, function (req, res) {
req.session.destroy();
res.send("logout success!");
});
//Getting Details endpoint
router.get("/data", auth, function(req, res) {
var collection = db.get('details');
collection.find({}, function(err, details){
if (err) throw err;
res.json(details);
});
});
After successful login req.session.admin is set to true. But, at Authentication middleware (auth), it is sending 401 status. Please help me solve this problem.
code:
//app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var getDetails = require('./routes/getDetails');
var app = express();
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', '*');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
// view engine setup
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.cookieParser());
app.use(express.static(path.join(__dirname, 'routes')));
app.use(express.session({
secret: '2C44-4D44-WppQ38S',
resave: true,
saveUninitialized: true
}));
app.use('/getDetails',getDetails);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
//app.listen(3001);
module.exports = app;
//getDetails.js
var express = require('express');
var router = express.Router();
var monk = require('monk');
var db = monk('localhost:27017/saidb');
// Login endpoint
router.post('/login', function (req, res) {
var collection = db.get("login");
//var data;
collection.find({}, function(err, details) {
//res.json(details);
if (!req.body.username || !req.body.password) {
res.send('login failed');
} else if(req.body.username === details[0].name && req.body.password === details[0].password ) {
req.session.admin = true;
var data = {
"status": "success",
"message": "login success!"
}
res.send(data);
} else {
var data = {
"status": "failure",
"message": "login failed"
}
res.send(data);
}
});
});
var auth = function(req, res, next) {
if (req.session && req.session.admin) {
console.log("success");
return next();
} else {
console.log("failed");
return res.sendStatus(401);
}
}
// Logout endpoint
router.get('/logout', auth, function (req, res) {
req.session.destroy();
res.send("logout success!");
});
//Getting Details endpoint
router.get("/data", auth, function(req, res) {
var collection = db.get('details');
collection.find({}, function(err, details){
if (err) throw err;
res.json(details);
});
});
//Get details by ID endpoint
router.get("/data:id", auth, function(req, res) {
var collection = db.get('details');
collection.find({id: parseInt(req.params.id)}, function(err, details){
if (err) throw err;
res.json(details);
});
});
//Adding Details endpoint
router.post("/data", auth, function(req, res) {
var collection = db.get("details");
collection.count({id : parseInt(req.body.id)},function(err,count){
if(!err){
if(count>0){
//send the response that its duplicate.
//console.log(errorororrrroror);
res.send("r");
}
}
});
console.log("request", req.body);
collection.insert({ id: parseInt(req.body.id),
website: req.body.website,
subtitle: req.body.subtitle,
url: req.body.url },
function(err, details) {
if(err) throw err;
res.json(details);
})
});
//Editing Details endpoint
router.put("/data", auth, function(req,res){
var collection = db.get("details");
collection.update({id: parseInt(req.body.id)},
{id: parseInt(req.body.id), website: req.body.website, subtitle: req.body.subtitle, url: req.body.url},
function(err, details){
if(err) throw err;
res.json(details);
})
});
//Deleting details endpoint
router.delete("/data", auth, function(req,res){
var collection = db.get("details");
collection.remove({id: parseInt(req.body.id)}, function(err, details){
if(err) throw err;
res.json(details);
})
});
module.exports = router;
Use these lines in your server file at top after express object like this
var app = express();
app.use(express.cookieParser());
app.use(express.session({secret: "sdsddsd23232323" }));
In below example for GET /api/users/i request secondMw is never executed even there is a next() call in firstMw. Why is that? How am I supposed to be able to run the secondMw?
var apiRouter = require('express').Router();
apiRouter.param('user', function firstMw(req, res, next, param) {
if(param === 'i'){
return next(); //jump to next mw sub-stack
}
next('route'); //continue with another matching route
}, function secondMw(req, res, next, param) {
console.log('NO, I AM NOT HERE. NEVER');
next();
});
apiRouter.get('/users/:user', function (req, res, next) {
res.json({
id: req.params.user
});
});
app.use('/api', apiRouter);
I don't see that router.params supports middleware stack (compare definition with app.get). But you can use ordered definition for same route.
'use strict';
let express = require('express');
let app = express();
app.use(require('body-parser').urlencoded({extended: false}));
var apiRouter = express.Router();
apiRouter.param('user', function mw1(req, res, next, param) {
console.log('MW1', param);
if (param === 'i')
next();
else
next('Error message'); // better next( new Error('Error message'));
});
apiRouter.param('user', function mw2(req, res, next, param) {
console.log('MW2', param);
next();
})
// If next() have params then Express calls handler error
apiRouter.use(function (err, req, res, next) {
console.log('Error: ', err)
res.send(err.message || err);
});
apiRouter.get('/users/:user', function (req, res, next) {
res.json({id: req.params.user});
});
app.use('/api', apiRouter);
app.listen(3000, function () {
console.log('Listening on port 3000');
});
Following is my server file. I am making 2 calls, one post and one get. It works fine at times. But gives an error of : Can't set headers after they are sent. Does this have anything to do with my client side code?
server.js
var express = require('express')
var mongoose = require('mongoose')
var path = require('path')
var bodyParser = require("body-parser")
var cors = require("cors")
var app = express()
var port = process.env.PORT || 3000
var Url = require("./data/url-schema");
//Express request pipeline
app.use(express.static(path.join(__dirname,"../client")))
app.use(bodyParser.json())
app.use(cors());
/*
Your server must be ready to handle real URLs. When the app first loads at / it will probably work, but as the user navigates around and then hits refresh at /dashboard your web server will get a request to /dashboard. You will need it to handle that URL and include your JavaScript application in the response.
*/
app.get('*', function (request, response, next){
response.sendFile(path.resolve(__dirname, '../client', 'index.html'))
next()
})
app.get('/:code', function(req, res) {
console.log("reg", req.params.code)
Url.findOne({code:req.params.code}, function(err, data){
console.log("data", data)
if(data)
res.redirect(302, data.longUrl)
else
res.end()
})
})
app.post('/addUrl', function (req, res, next) {
console.log("on create");
Url.findOne({longUrl:req.body.longUrl}, function(err, data) {
if (err)
res.send(err);
else if(data) {
console.log("already exists",data)
res.send("http://localhost:3000/"+data.code);
} else {
var url = new Url({
code : Utility.randomString(6,"abcdefghijklm"),
longUrl : req.body.longUrl
});
console.log("in last else data created",url)
url.save(function (err, data) {
console.log(data)
if (err)
res.send(err);
else
res.send("http://localhost:3000/"+data.code);
});
}
});
})
app.listen(port, function () {
console.log('Example app listening on port 3000!')
});
// Connect to our mongo database
mongoose.connect('mongodb://localhost/shortUrl');
I get the Following error
error
_http_outgoing.js:335
throw new Error('Can\'t set headers after they are sent.');
^
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:335:11)
at ServerResponse.header (/opt/lampp/htdocs/url-shortener/node_modules/express/lib/response.js:718:10)
at ServerResponse.location (/opt/lampp/htdocs/url-shortener/node_modules/express/lib/response.js:835:8)
at ServerResponse.redirect (/opt/lampp/htdocs/url-shortener/node_modules/express/lib/response.js:874:8)
at Query.<anonymous> (/opt/lampp/htdocs/url-shortener/server/server.js:30:8)
at /opt/lampp/htdocs/url-shortener/node_modules/mongoose/node_modules/kareem/index.js:177:19
at /opt/lampp/htdocs/url-shortener/node_modules/mongoose/node_modules/kareem/index.js:109:16
at process._tickCallback (node.js:355:11)
From the execution order, in * route handler, the body is being assigned to the response and then in /:code, the response code 302 is being added, where Location header is also added, hence the error. Any header must be added before the body to the response.
To solve this problem, simply change the order of the two GET statements.
Finally found the solution:
var express = require('express')
var mongoose = require('mongoose')
var path = require('path')
var bodyParser = require("body-parser")
var app = express()
var port = process.env.PORT || 3000
var Url = require("./data/url-schema")
var Utility = require("./utility")
//Express request pipeline
app.use(express.static(path.join(__dirname,"../client")))
app.use(bodyParser.json())
/*
Your server must be ready to handle real URLs. When the app first loads at / it will probably work, but as the user navigates around and then hits refresh at /dashboard your web server will get a request to /dashboard. You will need it to handle that URL and include your JavaScript application in the response.
*/
app.get('/dashboard', function (request, response, next){
response.sendFile(path.resolve(__dirname, '../client', 'index.html'))
next()
})
app.get('/about', function (request, response, next){
response.sendFile(path.resolve(__dirname, '../client', 'index.html'))
next()
})
app.get('/:code', function(req, res) {
Url.findOne({code:req.params.code}, function(err, data){
if(data){
res.redirect(302, data.longUrl)
}
})
})
app.post('/addUrl', function (req, res, next) {
Url.findOne({longUrl:req.body.longUrl}, function(err, data) {
if (err){
res.send(err)
}
else if(data) {
res.send("http://localhost:3000/"+data.code);
} else {
var newCode = getCode()
checkCode(newCode)
.then(function(data){
var url = new Url({
code : data,
longUrl : req.body.longUrl
});
url.save(function (err, data) {
if (err)
res.send(err);
else
res.send("http://localhost:3000/"+data.code);
});
})
}
});
})
app.listen(port, function () {
console.log('Example app listening on port 3000!')
});
// Connect to our mongo database
mongoose.connect('mongodb://localhost/shortUrl');
//Generate a random code
function getCode() {
return Utility.randomString(6,"abcdefghijklmnopqrstuvwxyz")
}
//Check if the code is unique
function checkCode(code) {
return new Promise(function (resolve, reject){
Url.findOne({code:code}, function(err, data) {
if(err === null){
resolve(code)
}else if(data){
saveUrlCode(getCode())
}
})
})
}
My earlier route which was :
app.get('*', function (request, response, next){
response.sendFile(path.resolve(__dirname, '../client', 'index.html'))
next()
})
The get route was getting executed twice on account of the above call and the
app.get(":/code") call.
So I had to handle the routes properly which I have done by handling the dashboard and about routes separately instead of using the "*" route.
I have a middleware setup in node to perform a task and call next upon success or failure. The task is called after an initial promise block runs. It is called in the .then function:
var Q = require('q');
var dataPromise = getCustomerId();
dataPromise
.then(function(data) {
getGUID(req, res, next);
}, function(error) {
console.log('Failure...', error);
});
};
The server hangs though because the (req,res,next) parameters are all undefined when in the context of the .then function.
Here is getCustomerId function:
var getCustomerId = function() {
var getCustomerIdOptions = {
options...
};
var deferred = Q.defer();
request(getCustomerIdOptions, function(err,resp,body){
if(err){
deferred.reject(err);
console.log(err);
return;
}else{
deferred.resolve(body);
}
});
return deferred.promise;
};
What would be the correct way to pass these parameters to the function called in the .then block?
EDIT:
The (req,res,next) parameters are from the outer function and are accessible when getGUID(req,res,next) is called outside of the .then() block.
var assureGUID = function(req, res, next) {
if(app.locals.guid){
next();
return;
}
var dataPromise = getCustomerId();
dataPromise
.then(function(data) {
getGUID(req, res, next)
}, function(error) {
console.log('Failure...', error);
}).;
};
Not sure what you are trying to do exactly, but you can call your promise function inside a express common middleware function like the next sample.
var express = require('express');
var $q = require('q');
var request = require('request');
var app = express();
// Middleware 1
app.use( function(req, res, next) {
console.log('i\'m the first middleware');
getCustomerId().then( function(body) {
console.log('response body', body);
return next();
},
function(err) {
console.log('Error on middlware 1: ', err);
});
});
// Middleware 2
app.use( function(req, res, next) {
console.log('i\'m the second middleware');
return next();
});
app.get('/', function(req, res) {
res.send('hi world');
});
app.listen(3000);
// Your custom function definition
function getCustomerId() {
var deferred = $q.defer();
request('http://someurltogetjsondata/user/id', function(err, resp, body) {
if(err) return deferred.reject(err);
deferred.resolve(body);
});
return deferred.promise;
}
I hope this helps a little, good luck.