I am trying to write a simple express server that accepts incoming JSON (POST), parses JSON and assigns the request body. The trick is I can't use bodyparser. Below is my server with a simple middleware function passed to app.use
Problem: whenever I send fictitious POST requests to my server with a superant (npm package that allows sending JSON through the terminal), my server shuts down. I wrote an HTTP server in a similar way using req.on ('data') ... so I'm at a dead end. Any tips?
const express = require('express'); const app = express(); function jsonParser(req, res, next) { res.writeHead(200, {'Content-Type:':'application/json'}); req.on('data', (data, err) => { if (err) res.status(404).send({error: "invalid json"}); req.body = JSON.parse(data); }); next(); }; app.use(jsonParser); app.post('/', (req, res) => { console.log('post request logging message...'); }); app.listen(3000, () => console.log('Server running on port 3000'));
source share