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

React POST requests with Express/Node and MongoDB

我正在编写程序,使用 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 只是一个 { } 我想知道我做错了什么?

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

在你的前端:

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 4.16 或更高版本,您可以只使用 express.json(),它会尝试解析请求 body 的 JSON 并将其保存到 req.body ,但前提是 header "Content-Type: application/json" 与请求一起发送:

const app = express();
app.use(express.json()); // Parses request body if type is json. Saves to req.body.