本文介绍了使用Express/Node和MongoDB响应POST请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm writing program that uses React as front-end, and an Express/Node API for the backend which then does CRUD operations in a MongoDB database. Right now, I'm using the native JS fetch() API to perform GET/POST operations on my front end. The GET requests work just fine, but my POST requests seem to not be working. On my front end, I have a form and a handler for form submission like so:

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>
    );
}

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

Then on my Express API, which is on port 5002, I have:

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只是一个{},我想知道自己做错了什么?

However, when the form is submitted, the request shows up on the Express API with an empty body. The console.log shows that req.body is just an { } I'm wondering what I did wrong?

推荐答案

使用 body-parser

在您的快递代码中添加:

in your express code add :

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));
    })
});

在您的收藏夹中:

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));
}

这篇关于使用Express/Node和MongoDB响应POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 03:22