I have an express route that looks like this:
app.post('/api/:type/*/*/*', apiRoute.api);
in my route file I have:
exports.api = function(req, res) {
var type = req.params.type;
var entity = req.params['0'];
var field = req.params['1'];
var params = req.params['2'];
switch (type)
{
case "get":
return {'entity' : entity, 'field' : field, 'params' : params}
break;
case "post":
break;
}
}
however when I go to
http://localhost:3000/api/get/industry/id/5
I get Cannot GET /api/get/industry/id/5
What am I doing wrong and what do I have to do to get it to return json?
Thanks!
You're defining a route for POST, and you're accessing it with a GET. If all you want to do is return some data from the server, you should define the route with GET:
app.get('/api/:type/*/*/*', apiRoute.api);
Otherwise, you should issue a POST request from the client to use the POST route you defined.
You can use app.route()
as a shortcut to the Router to define multiple requests on a route. Please see the sample below that use express 4
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
// ROUTES
var router = express.Router();
// apply the routes to our application
app.use('/', router);
// api routes
app.route('/api/:type/*/*/*')
.get(function(req, res) {
var type = req.params.type;
var entity = req.params['0'];
var field = req.params['1'];
var params = req.params['2'];
res.json({'entity' : entity, 'field' : field, 'params' : params});
})
.post(function(req, res) {
res.send('code to process post request goes here!');
});
// START THE SERVER
app.listen(port);
console.log('Server running on port ' + port);
Hopes this solves your problem..