最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

node.js - Using Fetch to put JSON in body of document - Javascript - Stack Overflow

programmeradmin1浏览0评论

I am trying to send JSON back to my express app with a POST method using fetch(). Here is my code:

 fetch('',{
                method:'POST',
                body:JSON.stringify({
                    csv: results
                })

Here is my post method in Express:

app.post("/canadmin", function(req,res){
var data = req.body.csv;
console.log(data);
//  r.db('cansliming').table('daily').insert( r.json(data) ).run(err, );
res.redirect("canadmin");
});

I get undefined through my console.log so I am unsure if I am getting my data correctly. What am I missing here? Is my fetch - body incorrect? That is what my guess is however I cannot figure out the correct syntax.

//***********EDIT-SOLUTION************//

I went to a Javascript meetup and a nice guy named Alex found the solution. The header was incorrect, we also added the mode:

fetch('/saveRecords',{
                headers: {
                        //This is the line we need for sending this data
                      'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
                },
                mode : 'no-cors',
                method:'POST',
                //This is the line we need actually send the JSON data
                body: JSON.stringify(results)
             }) //End fetch()

After doing this I was able to see it in my req.body in Express! I hope this helps someone.

I am trying to send JSON back to my express app with a POST method using fetch(). Here is my code:

 fetch('https://development.c9users.io/canadmin',{
                method:'POST',
                body:JSON.stringify({
                    csv: results
                })

Here is my post method in Express:

app.post("/canadmin", function(req,res){
var data = req.body.csv;
console.log(data);
//  r.db('cansliming').table('daily').insert( r.json(data) ).run(err, );
res.redirect("canadmin");
});

I get undefined through my console.log so I am unsure if I am getting my data correctly. What am I missing here? Is my fetch - body incorrect? That is what my guess is however I cannot figure out the correct syntax.

//***********EDIT-SOLUTION************//

I went to a Javascript meetup and a nice guy named Alex found the solution. The header was incorrect, we also added the mode:

fetch('/saveRecords',{
                headers: {
                        //This is the line we need for sending this data
                      'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
                },
                mode : 'no-cors',
                method:'POST',
                //This is the line we need actually send the JSON data
                body: JSON.stringify(results)
             }) //End fetch()

After doing this I was able to see it in my req.body in Express! I hope this helps someone.

Share Improve this question edited Sep 8, 2016 at 18:10 illcrx asked Aug 28, 2016 at 2:32 illcrxillcrx 8141 gold badge13 silver badges36 bronze badges 3
  • console.log(req.body) – enRaiser Commented Aug 28, 2016 at 2:35
  • I did that and it just gave { } – illcrx Commented Aug 28, 2016 at 3:25
  • Is any specific reason, you are converting body in String during request time? – abdulbari Commented Aug 28, 2016 at 6:10
Add a ment  | 

3 Answers 3

Reset to default 2

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/json
app.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...});
发布评论

评论列表(0)

  1. 暂无评论