简体   繁体   English

如何使用 express nodejs 接收 axios 发布请求的正文?

[英]how can i receive the body of an axios post request with express nodejs?

my browser side js code:我的浏览器端js代码:

import axios from 'axios';

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

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

my nodejs code:我的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);
});

my node js output:我的节点 js output:

server listening on port 3000
{}

my browser console output:我的浏览器控制台 output:

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

please look that I'm alredy using a parser body middleware, the request is working fine but for some reason the server cant get the request body.请看我已经在使用解析器主体中间件,请求工作正常,但由于某种原因服务器无法获取请求主体。

You have to use app.use(express.json())你必须使用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');
});

You also have to update your ajax request with following:您还必须使用以下内容更新您的 ajax 请求:

contentType: "application/json",
data: JSON.stringify(hellodata),

Make sure to use body-parser for Express.确保使用 Express 的 body-parser。 In case, your project depends on some generated boilerplate code, it's most likely already included in your main server script.如果您的项目依赖于一些生成的样板代码,它很可能已经包含在您的主服务器脚本中。 If not:如果不:

var bodyParser = require('body-parser'); app.use(bodyParser.json());

npm install body-parser --save

now get body of your request in nodejs现在在 nodejs 中获取您的请求body

app.post('/create', (req, res, next) => { console.log(req.body); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM