简体   繁体   English

req.body 的值为 undefined REST API

[英]The value of req.body is undefined REST API

I am creating REST API application.我正在创建 REST API 应用程序。 I have front-end (Nuxt.js) and API (Express.js), and I am trying to send data from front-end to API.我有前端 (Nuxt.js) 和 API (Express.js),我正在尝试将数据从前端发送到 API。 Api works on port 3001 and front on port 8010. Api 在端口 3001 上工作,在端口 8010 上工作。

So, the sending of data looks like this:所以,数据的发送看起来像这样:

Function on front:正面功能:

  methods: {
    async postTip() {
      const test = await postTipFunc({
        content: this.tipContent
      })
    }
  }

Here is postTipFunc function (project_front/api/index.js) :这是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
}

Here is end-point which goes to back-end (project_front/server/routes/index.js) :这是进入后端(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

And finally back-end (prodect_api/src/routes/index.js) :最后是后端(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;

Actually, that function tipController.postTip just receive data and shows it in console, so, it makes no sense to show it.实际上, tipController.postTip函数只是接收数据并在控制台中显示它,因此,显示它是没有意义的。

Also, if it can help, console.log() shows data only here - project_front/api/index.js .此外,如果有帮助, console.log()仅在此处显示数据 - project_front/api/index.js After that point everything is undefined在那之后一切都undefined

So, how can I fix it?那么,我该如何解决呢?

Okey, here is answer, to make things work you need to install body-parse into your API.好的,这是答案,要使事情正常进行,您需要将body-parse安装到您的 API 中。 Just like that:就像这样:

const bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

Hope, it'll help someone!希望,它会帮助某人!

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

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