[英]The value of req.body is undefined REST API
我正在創建 REST API 應用程序。 我有前端 (Nuxt.js) 和 API (Express.js),我正在嘗試將數據從前端發送到 API。 Api 在端口 3001 上工作,在端口 8010 上工作。
所以,數據的發送看起來像這樣:
正面功能:
methods: {
async postTip() {
const test = await postTipFunc({
content: this.tipContent
})
}
}
這是postTipFunc
函數(project_front/api/index.js)
:
import axios from "axios";
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'
const api = axios.create({
baseURL: 'http://localhost:8010/',
headers: {
'Content-Type': 'application/json'
}
})
export const postTipFunc = async payload => {
const { data } = await api.post(`p-t`, payload)
return data
}
這是進入后端(project_front/server/routes/index.js)
的端點:
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'
const { Router } = require('express')
const axios = require('axios')
const dotenv = require('dotenv')
dotenv.config()
const api = axios.create({
baseURL: "http://localhost:3001/",
})
const router = Router()
router.post(`/p-t`, async (req, res) => {
try {
const data = await api.post(`/post-tip`, req.body)
res.json(data.data)
} catch (e) {
console.log(e)
}
})
module.exports = router
最后是后端(prodect_api/src/routes/index.js)
:
const router = require('express').Router();
const wrapAsync = require('./../middlewares/async')
const tipController = require('../controllers/tip')
router.post(
"/post-tip",
wrapAsync(tipController.postTip)
)
module.exports = router;
實際上, tipController.postTip
函數只是接收數據並在控制台中顯示它,因此,顯示它是沒有意義的。
此外,如果有幫助, console.log()
僅在此處顯示數據 - project_front/api/index.js
。 在那之后一切都undefined
那么,我該如何解決呢?
好的,這是答案,要使事情正常進行,您需要將body-parse
安裝到您的 API 中。 就像這樣:
const bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
希望,它會幫助某人!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.