Enable POST/REST requests in grunt-contrib-connect
My Task
Mocking some API responses with grunt-contrib-connect and some custom middleware functions.
My Problem
405 Method not allowed
responses for POST requests
Let's get the party started.
First naive (search stackoverflow, c&p) approach:
- add a function that sets all required HTTP headers
var enableREST = function(req, res, next){
res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
res.setHeader('Access-Control-Allow-Credentials', true);
res.setHeader('Access-Control-Allow-Methods', 'GET,HEAD,PUT,PATCH,POST,DELETE');
res.setHeader('Access-Control-Allow-Headers', req.headers['access-control-request-headers']);
return next();
};
- add that function to grunt-contrib-connect middlewares
connect: {
server: {
options: {
middleware: function(connect, options, middlewares) {
middlewares.push(enableREST);
}
}
}
}
Didn't turned out so well. Even various other header combinations didn't work. Still the same response: 405 Method not allowed
.
My Solution
After a while and some code reviews I found this 'little return; trap' in expressjs/serve-index bypassing my custom middleware.
All I had to do was queueing enableREST()
in front of serveIndex()
by unshifting instead of pushing it to the middlewares array:
connect: {
server: {
options: {
middleware: function(connect, options, middlewares) {
middlewares.unshift(enableREST);
}
}
}
}
Response: 200 OK
Written by Andi
Related protips
1 Response
All I get is:
Running "connect:server" (connect) task
Fatal error: Cannot call method 'unshift' of undefined
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Node
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#