简体   繁体   中英

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:

[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.

 '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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM