Express.js response status code with jsonp payload

I have a MEAN stack backend where I would like to answer

return res.status(400).jsonp({ message: 'Parsing failed.', code: '123' }); 

When an angular application uses this JSONP endpoint and encounters this particular error, it gets 400, but without its payload. When I change the status to 200/300, it reaches a fine, but 400/500 - not.

On other routes (POST) I can respond with a status code and a 4 ** payload without any problems.

 return res.status(400).send({ message: 'Codes do not match.', code: '234' }); 

Any idea that I don't notice about?

+6
source share
1 answer

It looks like it's a browser: when a remote script is requested (as is the case with JSONP requests) and the response returns 400 HTTP status (or higher), any code that can still get returned in the response body is not evaluated (it really makes sense )

Angular will only know that the response was sent and that it had an error status, but since the callback was not called, there is no payload data to send the callback.

I tested a standalone HTML page:

 <script> function foo(data) { alert('foo') } </script> <script src="/endpoint?callback=foo"></script> 

And the following express handler:

 app.get('/endpoint', (req, res) => { return res.status(400).jsonp({ hello : 'world' }); }); 

State 400 does not raise a warning, state 200. It also does not work if the handler returns a simple JS (acts like a simple .js file that is loaded using <script src=...> ).

So, for JSONP requests, you must adhere to 200 responses and pass any errors in some other way (for example, set the error property in the response object).

+2
source

All Articles