req.body of the empty Node.js in the angular

Asked

Viewed 54 times

1

Good afternoon

I am creating an API in Node.js and I am having problems with req.body received by express. The problem comes down to not being able to get the post Rest variables sent by angualr9, when I create a form and direct to the path of the file Node.js it finds the variables but in the angular Rest the variables come in the file (with you in the browser debug) but it doesn’t make it to the server. Thank you for your attention.


const bodyParser = require('body-parser');
const express = require('express');

const config = require('../../config/config');
const port = config.server.port;

const servPontoDeVenda = require('../../api/pages/loja/pdv');

const app = express();

app.use(bodyParser.urlencoded({ extended:true}));
app.use(bodyParser.json());

app.use(function (req, res, next) {

    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
    res.setHeader('Access-Control-Allow-Headers', 'content-type');
    res.setHeader('Content-Type', 'application/json');
    res.setHeader('Access-Control-Allow-Credentials', true);
    next();
});

app.get('/get', (req, res) => {
    res.json(servPontoDeVenda.get(req));
});

app.post('/post', function (req, res) {
    console.log('bod', req.body); //esta vindo vazio
    res.json(servPontoDeVenda.post(req));
});

app.listen(port, () => {
    console.log(`Example app listening at http://localhost:${port}`);
});

  • no error in nodejs code, ran here, and sending correctly: $ curl -d '{"teste": 42}' -H 'content-type: application/json' http://localhost:3000/post the data arrives: bod { teste: 42 } your error is in the frontend layer.

  • I tested the tb code, when sending json is ok, the problem is when sending formdata. Probably this is the method of sending via html form.

  • Could you send me the format that vcs are sending on the front end? The funny thing is that I already use this method on the front end for a PHP api.

  • does the opposite, says how you are sending.. what type? is going to form data?

  • Dude I found the error for php api I have a treated method to receive and send data all goes through this method and it uses JSON.stringify(objJSON) and this was damaging or something like Node.js. Thank you so much for the tip.

1 answer

1

This content is outdated!

REMOVE:

app.use(bodyParser.urlencoded({ extended:true}));
app.use(bodyParser.json());`insira o código aqui`;

USE:

app.use(express.json());
  • Thanks, buddy, I got it. in my case it was the angular that was with the JSON.stringify() method to send to PHP in this unnecessary case to Node.js

Browser other questions tagged

You are not signed in. Login or sign up in order to post.