我如何通过express nodejs接收axios发布请求的正文?

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

我的浏览器端js代码:

import axios from 'axios';

var testObject = {
   field : 'this is a test field'
}

axios.post('/create', testObject)
.then((res) => {
   console.log(res);
});

我的nodejs代码:

const express = require('express');
const path = require('path');

const app = express();

//middlewares
app.use(express.urlencoded({extended: false}));
app.use(express.static(path.resolve(__dirname, '../dist')));

app.post('/create', (req, res) => {
  console.log(req.body);
  res.send('this is the server response');
});

const port = 3000;
app.listen(port, () => {
  console.log('server listening on port ' + port);
});

我的节点js输出:

server listening on port 3000
{}

我的浏览器控制台输出:

{data: "this is the server response", status: 200, statusText: "OK", headers: {…}, config: 
{…}, …}

请注意,我很喜欢使用解析器主体中间件,请求运行正常,但由于某种原因服务器无法获取请求主体。

javascript node.js express post axios
1个回答
0
投票

您必须使用app.use(express.json())

// parse application/json
server.use(express.json());

app.post('/create', (req, res) => {
  console.log(req.body);
  res.send('this is the server response');
});

您还必须使用以下内容更新ajax请求:

contentType: "application/json",
data: JSON.stringify(hellodata),
© www.soinside.com 2019 - 2024. All rights reserved.