Invalid JSON GET Express.js request

When writing the API, I came across a very complex error: when I try to make res.send(INSERT JSON) with the heading Content-Type application/json (by default for most AJAX), I get an invalid json error, When I set the content type to what or else (e.g. text/plain ), I get the correct answer, but to use some front-end frameworks I need to support application/json . Here is the error message:

 Error: invalid json at Object.exports.error (/Users/Brad/node_modules/express/node_modules/connect/lib/utils.js:44:13) at IncomingMessage.module.exports (/Users/Brad/node_modules/express/node_modules/connect/lib/middleware/json.js:68:73) at IncomingMessage.EventEmitter.emit (events.js:85:17) at IncomingMessage._emitEnd (http.js:366:10) at HTTPParser.parserOnMessageComplete [as onMessageComplete] (http.js:149:23) at Socket.socket.ondata (http.js:1680:22) at TCP.onread (net.js:410:27) 

My server code is below:

 app.configure(function () { app.use(express.bodyParser()); app.use(express.cookieParser('SALT')); app.use(express.static(__dirname + '/static/')); app.use(express.session()); }); app.get('/users', function(req, res) { res.send({'test': 'test'}); }); 

Here is a picture of my Postman installation - I am using the Chrome Postman extension to test my API: enter image description here

+4
source share
1 answer

I believe the problem is that you want to use the Content-Type header in the server response; the Content-Type header is not in your request.

When you use the Content-Type header in your request, Express will read the Content-Type and try to interpret the information provided as this Content-Type, in this case, as JSON. Since this is a GET request and therefore does not have a body, Express tries to interpret the empty string as JSON, which gives you an error.

+4
source

Source: https://habr.com/ru/post/1484006/


All Articles