I am creating REST API application. I have front-end (Nuxt.js) and API (Express.js), and I am trying to send data from front-end to API. Api works on port 3001 and front on port 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)
:
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)
:
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)
:
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.
Also, if it can help, console.log()
shows data only here - project_front/api/index.js
. After that point everything is undefined
So, how can I fix it?
CodePudding user response:
Okey, here is answer, to make things work you need to install body-parse
into your API. Just like that:
const bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
Hope, it'll help someone!