为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

LEATH 2022-08-04 09:42:09
我的浏览器端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();//middlewaresapp.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: {…}, …}请看,我正在使用解析器正文中间件,请求工作正常,但由于某种原因服务器无法获得请求正文。
查看完整描述

2 回答

?
慕神8447489

TA贡献1780条经验 获得超1个赞

您必须使用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),


查看完整回答
反对 回复 2022-08-04
?
哔哔one

TA贡献1854条经验 获得超8个赞

确保对 Express 使用正文解析器。如果您的项目依赖于某些生成的样板代码,它很可能已经包含在主服务器脚本中。如果不是:


var bodyParser = require('body-parser');

app.use(bodyParser.json());


npm install body-parser --save


现在在 nodejs 中获取您的请求body


app.post('/create', (req, res, next) => {

  console.log(req.body);

});


查看完整回答
反对 回复 2022-08-04
  • 2 回答
  • 0 关注
  • 92 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信