亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

我如何通過快速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 關注
  • 124 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號