Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I receive a json in express server

I need to receive a JSON from my front in React. But the JSON comes to me in a strange way (an object with the data in string), I don’t know how to return it to type object again.

I send this.

const data = {
        email: 'emailc@email.com',
        password: 'test'
    }
    const options = {
        method: 'POST',
        body: JSON.stringify(data),
        mode: 'no-cors',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    }

    const onsubmit = (e) => {
        //evitamos que se haga la peticion en automatico
        e.preventDefault();
        fetch('http://localhost:3001/user/signin',options)
        .then(res => res.json())
        .catch(error => console.error('Error:', error))
        .then(response => console.log('Success:', response));
        console.log('send on submit');
    }

and I get this on the express server:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[Object: null prototype] {
  '{"email":"emailc@email.com","password":"test"}': ''
}

My server is configured in this way:

const express = require('express');
const app = express();
const morgan = require('morgan');
const cors = require('cors');
const {mongoose} = require('./src/database/connection')

const Parser = require("body-parser").urlencoded({ extended: false });

//config
app.set('port', process.env.PORT || 3001);


//middlewares
app.use(morgan('dev'));
app.use(Parser);
app.use(cors()); //accepts connection from all directions

//Routes
app.use(require('./src/test'));
app.use(require('./src/routes/users'));

//Server
app.listen(app.get('port'), (req, res) => {
    console.log(`Server on port ${app.get('port')}`);
})

I think I have misconfigured the body-parser, please help, it is my first API.

>Solution :

'Content-Type': 'application/x-www-form-urlencoded'

If you tell the server you are sending Form Encoded data then it is going to try to parse what you send as Form Encoded data.

Don’t lie.

If you are sending JSON, say so:

'Content-Type': 'application/json'

const Parser = require("body-parser").urlencoded({ extended: false });

You also need a body parser that supports JSON.

const Parser = require("body-parser").json();

But Express has a built-in body parser and variable names starting with capital letters are traditionally reserved for constructor functions / classes.

const parser = express.json();

Aside:

mode: 'no-cors'

If you are making a cross-origin request then that will break it.
If you are making a same-origin request then that will do nothing.

Remove it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading