使用Express / Node和MongoDB响应POST请求

问题描述 投票:1回答:2

我正在编写使用React作为前端的程序,以及用于后端的Express / Node API,然后在MongoDB数据库中执行CRUD操作。现在,我正在使用本机JS fetch()API在我的前端执行GET / POST操作。 GET请求工作正常,但我的POST请求似乎无法正常工作。在我的前端,我有一个表单和表单提交处理程序,如下所示:

handleSubmit(){
    let databody = {
        "name": this.state.nameIn,
        "quote": this.state.quoteIn
    }

    return fetch('http://localhost:5002/stored', {
        method: 'POST',
        body: JSON.stringify(databody),
        headers: {
            'Content-Type': 'application/json'
        },
    })
    .then(res => res.json())
    .then(data => console.log(data)); 
}


render(){
    return (
        <div>
            <form onSubmit={this.handleSubmit}>
                <label>
                    Name
                    <input type="text" name="name" value={this.nameIn} onChange={this.handleNameChange}/>
                </label>
                <label>
                    quote
                    <input type="text" name="quote" value={this.quoteIn} onChange={this.handleQuoteChange}/>
                </label>
                <input type="submit" value="Add to DB" />
            </form> 
        </div>
    );
}

然后在我的Express API上,在端口5002上,我有:

app.post('/stored', (req, res) => {
    console.log(req.body);
    db.collection('quotes').insertOne(req.body, (err, data) => {
        if(err) return console.log(err);
        res.send(('saved to db: ' + data));
    })
});

但是,在提交表单时,请求会在Express API上显示为空主体。 console.log显示req.body只是一个{}我想知道我做错了什么?

node.js mongodb reactjs express crud
2个回答
2
投票

使用body-parser

在您的快递代码中添加:

global.bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({
  extended: true,
  limit: '50mb',
  parameterLimit: 100000
}))
app.use(bodyParser.json({
  limit: '50mb',
  parameterLimit: 100000
}))


app.post('/stored', (req, res) => {
    console.log(req.body);
    db.collection('quotes').insertOne(req.body, (err, data) => {
        if(err) return console.log(err);
        res.send(('saved to db: ' + data));
    })
});

在你的froontend中:

handleSubmit:function(e){
   e.preventDefault();
    let databody = {
        "name": this.state.nameIn,
        "quote": this.state.quoteIn
    }

    fetch('http://localhost:5002/stored', {
            method: 'POST',
            body: JSON.stringify(databody),
            headers: {
                'Content-Type': 'application/json'
            },
        })
        .then(res => res.json())
        .then(data => console.log(data));
}

0
投票

如果您使用express 4.16或更高版本,您可以使用express.json(),它将尝试解析请求正文的JSON并将其保存到req.body,但仅当标题“Content-Type:application / json”与请求:

const app = express();
app.use(express.json()); // Parses request body if type is json. Saves to req.body.
© www.soinside.com 2019 - 2024. All rights reserved.