0

I´m using nodejs to make a server what connect with a DB and a simple website, i can do a GET fetch and i take the data, but when i do a POST fetch my server receive and empty request.body.I try 2 diferents versions of nodejs 12.16.1 and 16.10.0 also i use express and body-parser and i got the same result.

This is my config on the server site

const express = require('express');
const morgan = require('morgan');
const app = express();

const router = require('../routes/routes.js');
/**configuraciones */

app.set('port',3000);

app.use(morgan('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(router);


app.listen(app.get('port'), () =>{
    console.log("El server esta operativo ")
});

This is my code on website

var username = document.getElementById('user-reg');
var emailreg = document.getElementById('email-reg');
var btnReg = document.getElementById('btn-reg')
btnReg.addEventListener('click', sacarInformacion)

function sacarInformacion(){
    var user = username.value
    var email = emailreg.value
    var jsonString = `{"correo": "${email}", "nombre":"${user}"}`
    const options = {
        method : 'POST',
        mode: 'no-cors',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        },
        body: JSON.parse(jsonString)
    }
    fetch('http://localhost:3000/to', options);
    console.log(JSON.parse(jsonString))
    //i catch in the console the data i pass on body
}

The main problem is that i used postman as API and i get the body on the server, but when i use it on website i get an empty body

  • You said `mode: 'no-cors'` so you can't do anything that requires permission via CORS - including setting the `content-type` header that the body parsing middleware depends upon to know it needs to parse JSON. – Quentin Apr 20 '22 at 22:46
  • `body: JSON.parse(jsonString)` — You're also converting your JSON to a plain object before passing it to `fetch` … which will break it. If you want to send JSON then send JSON. – Quentin Apr 20 '22 at 22:46
  • ```var jsonString = `{"correo": "${email}", "nombre":"${user}"}`;``` — Don't construct JSON by mashing strings together. It will fail to escape things correctly. Make an object then use `JSON.stringify`. – Quentin Apr 20 '22 at 22:47

0 Answers0