Reputation: 28349
I'm running Node.js with Express.js and everything works perfectly until someone sends invalid JSON with content-type text/json and then my server responds with a 400.
Now, I realize this is "correct" but I'd like to intercept the incoming data and see if I can fix the data by replacing all the new lines (\n \r) with the string representations thereof ("\n", "\r") because that appears to be the problem with the incoming request. Specifically, the json has instances that look like
{"foo":"bar
and so forth"}
Where the line breaks are some combination of \n and \r.
I'm not seeing where I can look-at/massage the incoming request data before it gets bounced as a 400.
Upvotes: 0
Views: 2577
Reputation: 707308
This is precisely what middleware is all about. Just insert a middleware handler as the very first handler (before anything else that might look at the request data such as app.use(BodyParser.json())
) and it gets first crack at every request and it can modify the request object as it wants to before any of your other handlers see the data.
// make this the first request handler for Express
app.use(function(req, res, next) {
// examine req here and make any changes as desired
// when done, call next()
next();
});
If it's a GET request, the data is all there. If it's a POST request, you will you have to actually read the request stream to get the data before you can process it. This probably means you have to actually replace bodyParser.json()
with your own unless you replace the request stream with a new stream.
Upvotes: 4