Using Fetch to put JSON in body of document - Javascript
slightly different solution worked for me. body-parser does not handle multipart/form-data
bodies
client side fetch
call sends data to express:
fetch('api/users', { headers: { 'Content-Type': 'application/json' }, // tells the server we have json method:'PUT', // can be POST body: JSON.stringify(results), // json is sent to the server as text})
server side express app
listens for application/json
and parses it to json:
const express = require('express')const app = express()// parse application/jsonapp.use(bodyParser.json())
After setting up the bodyParser
I defined an express middleware function
app.put('/api/:collection', (req, res) => { logger.log('put', req.body) // ...})
the req.body
is json.
Normally, you're going to have to read from the req
like a stream. Something like this:
var body = '';req.on('data', function (chunk) { body += chunk;});req.on('end', function () { console.log(JSON.parse(body));});
A better solution is to use the body-parser middleware.
It will be better to use body-parser middleware for post method.
for example pseudocode: (in ES6 format)
including body-parser:
import bodyParser from 'body-parser';const urlEncode = bodyParser.urlencoded({extended: false});
now, use that on api post request like this:
app.post('/something_url', urlEncode, (req, res) => { ...your code here...});