I am creating a MERN application, where I am trying to send a post request to my backend, however when i log the req.body from my backend, it is empty
const removeTour = (id) => {
const getDevices = async () => {
const settings = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ name: 'here', info: '1', image: '1', price: '1' })
};
try {
const fetchResponse = await fetch(`http://localhost:3080/add-tour`, settings);
const data = await fetchResponse.json();
return data;
} catch (e) {
return e;
}
};
getDevices();
const newTours = tours.filter((tour) => tour._id !== id);
setTours(newTours);
};
The function is called when the button is pressed.
On the backend, i have an app.post, which should receive the request. THe request.body received is empty
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cors = require('cors');
require('dotenv').config();
const data = require('./data.json');
//dotenvs
const DBLink = process.env.DB_HOST;
const port = process.env.PORT;
const home = process.env.HOME;
//app
const app = express();
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
//shema
const TourSchema = mongoose.Schema({
name: {
type: String,
required: true
},
info: {
type: String
// required: true
},
image: {
type: String
// required: true
},
price: {
type: String
// required: true
}
});
const Tour = mongoose.model('tour', TourSchema);
//app routes
app.get('/', (req, res) => {
(async () => {
const tours = await Tour.find((data) => data);
try {
res.json(tours);
} catch (error) {
console.log(error);
}
})();
});
app.post('/add-tour', (req, res) => {
console.log(req.body);
// const { name, image, info, price } = req.body;
// const tour = new Tour({ name, image, info, price });
// tour.save();
// res.status(201).redirect('http://localhost:3000/');
res.send('here');
});
//mongoose
mongoose
.connect(DBLink, {
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true,
useNewUrlParser: true
})
.then(() => {
app.listen(port, () => console.log(`Server is running on ${port}`));
})
.catch((err) => console.log(err));
All i get in the terminal is -
terminal:
{}
However when i am making a post request from a html form, with input that has a value and a name, the received request has the body
question from:
https://stackoverflow.com/questions/65901415/when-creating-a-mern-application-i-need-to-create-a-post-request-from-frontend 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…