I'm trying to use grunt serve
with the connect-rest middleware. I tried to configure connect-rest
in my Gruntfile.js
which worked for GET requests, but not for POST. I wonder what I'm missing out. This is my Gruntfile.js (excerpt):
module.exports = function (grunt) {
var postResponder = function(request, content, callback) {
callback(null, {Status : 42});
}
var Rest = require('connect-rest');
var rest = Rest.create( {context: '/'} );
rest.assign(['get'],'/*', postResponder);
...
livereload: {
options: {
open: true,
middleware: function (connect) {
return [
connect().use(rest.processRequest()),
connect.static('.tmp'),
connect().use('/bower_components', connect.static('./bower_components')),
connect().use('/app/styles', connect.static('./app/styles')),
connect.static(appConfig.app)
];
}
}
},
That works like a charm. But when I change that one line to:
rest.assign(['post'],'/*', postResponder);
or
rest.assign('*','/*', postResponder);
Then on posting I get the following entry in the log (running grunt --debug):
[D] server POST /api/groups.json?cache=false&force=true&requesttime=2015-10-29T06:46:24.443Z 404 103 - 2.027 ms
and a 404 error when posting (get works).
What do I miss?
It turned out, that for my purpose - being able to support post of JSON as a mock I didn't need connect-rest in the first place. The build in capabilities of connect provided all I needed. So the start of the Gruntfile.js
now looks like this:
module.exports = function (grunt) {
var bodyParser = require("body-parser");
var postResponder = function(request, response, next) {
if (request.method === 'POST') {
console.log(request.method+" "+request.url);
response.setHeader('Content-Type', 'application/json');
response.statusCode = 200;
response.end(JSON.stringify(request.body));
} else {
next();
}
};
and the livereload
section like this:
livereload: {
options: {
open: true,
middleware: function (connect) {
return [
connect().use('/api', bodyParser.json()),
connect().use('/api', postResponder),
connect.static('.tmp'),
connect().use('/bower_components',
connect.static('./bower_components')),
connect().use('/app/styles', connect.static('./app/styles')),
connect.static(appConfig.app)
];
}
}
}
Note: I limit postbacks to calls to /api here - you might need different endpoints. The example simply echos back the JSON received.