Problem receiving the Body in NodeJS from JavaScript

0

How do I send the fetch to the backend?

onSubmit (e) {
        var random = stringGen(6);
        e.preventDefault();
        let details = new FormData();
        details.append('demo_id', random);
        details.append('description', this.state.description);
        details.append('url', this.state.url);

      
        fetch (backend+'/api/demos/create/details', {
          method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: details
    })
        .then(() => {
          location.reload();
        });
      }

How the req.body arrives in the backend

How can I make it arrive as a simple json

Something like this

{
   dato : valor,
   dato : valor
}
    
asked by Santiago D'Antuoni 14.03.2017 в 18:04
source

3 answers

1

First of all, be consistent with what you want to do. If you are going to send non-binary data, use JSON; otherwise, use FormData to send binary data as File objects.

If the case is that you want to send binary data and also standard values, in this case you would need to use multer . Multer also allows you to obtain the other data that are not binary by means of fields() :

router.post('/tu-url', upload.fields(), function (req, res, next) {
    console.log(req.body); // disponible los campos estándar
});

In all other cases, send a JSON:

  

It is necessary to send the JSON as a string.

fetch (backend+'/api/demos/create/details', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      demo_id: random,
      description: this.state.description,
      url: this.state.url
    })
});

Note: Remember to add bodyParser for Express to parse the JSONs and FormData :

// para urlencoded data
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
    
answered by 14.03.2017 / 18:43
source
2

If you want it to arrive as a JSON, you should build a JSON in the first place.

var details = {
    demo_id: random,
    decription: this.state.description,
    url: this.state.url
};

Then, you should send it as "application / json":

fetch (backend+'/api/demos/create/details', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify(details)
})

Assuming the rest is good (backend), you should walk.

If you do not want to change the way you send the form, you can add the body-parser with express: Link to Github

    
answered by 14.03.2017 в 18:23
0

add the line in your Nodejs app file the following line:

app.use (bodyParser.json ());

, as long as you use express and body-parser ( var express = require ("express"); var app = express (); var bodyParser = require ("body-parser"); )

    
answered by 14.03.2017 в 18:51