I created nodejs api and react app and I dockerized them.
When I try to send a post request through api, the request body getting empty.
I created api docker container like this:
FROM node:lts
# Create app directory
WORKDIR /app
# Install app dependencies
COPY package*.json ./
RUN npm install
# Copy app source code
COPY . .
#Expose port and start application
EXPOSE 4000
CMD [ "npm", "start" ]
I also created react app container like this:
FROM node:latest
WORKDIR /app
COPY package.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["npm", "start"]
I double checked to express json middleware in nodejs:
app.use(express.urlencoded());
app.use(express.json());
I am sending post request like this in react app:
fetch(`${serviceUrl}/metrics`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(getPerfanalytics().values),
})
I can see that request is working good but the request body is empty always.
Here is how can I get post request:
export const saveMetric = (req, res) => {
let params = req.body;
console.log(params);
if (typeof params === 'string') {
params = JSON.parse(params)
}
new Metric(params).save().then(metric => {
res.json({
message: 'Metric saved',
data: metric
});
}).catch((err) => {
res.status(500);
res.json({
message: 'Metric saving error',
error: err
});
}
);
}
How can I solve this problem?
Thanks