我如何通过快速nodejs接收axios帖子请求的主体?

我的浏览器端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: 

{…}, …}

请看,我正在使用解析器正文中间件,请求工作正常,但由于某种原因服务器无法获得请求正文。


LEATH
浏览 94回答 2
2回答

慕神8447489

您必须使用app.use(express.json())// parse application/jsonserver.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),

哔哔one

确保对 Express 使用正文解析器。如果您的项目依赖于某些生成的样板代码,它很可能已经包含在主服务器脚本中。如果不是:var bodyParser = require('body-parser');app.use(bodyParser.json());npm install body-parser --save现在在 nodejs 中获取您的请求bodyapp.post('/create', (req, res, next) => {  console.log(req.body);});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript