最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

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

matteradmin6PV0评论

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...});
Post a comment

comment list (0)

  1. No comments so far