简体   繁体   English

如何在快递服务器中接收 json

[英]How can I receive a json in express server

I need to receive a JSON from my front in React.我需要从我的 React 前面收到 JSON。 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.但是 JSON 以一种奇怪的方式出现在我面前(带有字符串数据的 object),我不知道如何将其返回到再次键入 object。

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.我想我错误地配置了正文解析器,请帮忙,这是我的第一个 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:如果您要发送 JSON,请这样说:

'Content-Type': 'application/json'

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

You also need a body parser that supports JSON.您还需要一个支持 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.但是 Express 有一个内置的主体解析器,并且以大写字母开头的变量名传统上是为构造函数/类保留的。

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.去掉它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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