创建MERN应用时,需要创建一个POST从前端到后端的请求,但是请求体是空的
When creating a MERN application, I need to create a POST request from frontend to the backend, but the request body is empty
我正在创建一个 MERN 应用程序,我试图在其中向我的后端发送一个 post 请求,但是当我从我的后端记录 req.body 时,它是空的
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);
};
按下按钮时调用该函数。
在后端,我有一个 app.post,它应该接收请求。 request.body收到的是空的
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));
我在终端中得到的是 -
终端:
{}
然而,当我从 html 表单发出 post 请求时,输入具有值和名称,收到的请求具有正文
您可能在应用 body-parser 时遇到了一些问题。检查以下官方示例 https://github.com/expressjs/body-parser “Express/Connect 顶级通用”。如果您添加 app.use(bodyParser.json()) 它应该正确解析 json。
我正在创建一个 MERN 应用程序,我试图在其中向我的后端发送一个 post 请求,但是当我从我的后端记录 req.body 时,它是空的
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);
};
按下按钮时调用该函数。 在后端,我有一个 app.post,它应该接收请求。 request.body收到的是空的
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));
我在终端中得到的是 - 终端: {}
然而,当我从 html 表单发出 post 请求时,输入具有值和名称,收到的请求具有正文
您可能在应用 body-parser 时遇到了一些问题。检查以下官方示例 https://github.com/expressjs/body-parser “Express/Connect 顶级通用”。如果您添加 app.use(bodyParser.json()) 它应该正确解析 json。