Javascript I';我在express.js中得到了空的请求正文
我试图在数据库中获取数据,但在请求正文中没有获取任何内容。我已经使用了parse body和CORS,但它仍然不起作用。 我尝试了几件事,但都没有成功。 后端代码:Javascript I';我在express.js中得到了空的请求正文,javascript,express,Javascript,Express,我试图在数据库中获取数据,但在请求正文中没有获取任何内容。我已经使用了parse body和CORS,但它仍然不起作用。 我尝试了几件事,但都没有成功。 后端代码: const bodyParser = require('body-parser'); const cors = require('cors'); const port = 5000; const app = express(); app.use(cors()); app.use(bodyParser.json()); cons
const bodyParser = require('body-parser');
const cors = require('cors');
const port = 5000;
const app = express();
app.use(cors());
app.use(bodyParser.json());
const MongoClient = require("mongodb").MongoClient;
const uri = "mongodb+srv://ishadDB@cluster0.gi4fd.mongodb.net/?retryWrites=true&w=majority";
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
client.connect((err) => {
const bookings = client.db("BurjAlArab").collection("bookings");
console.log("Connected");
app.post('/addBooking', (req, res) => {
console.log(req)
const newBooking = req.body;
console.log(newBooking);
bookings.insertOne(newBooking)
.then(res => {
res.send(result.insertedCount > 0);
});
});
});
app.get("/", (req, res) => {
res.send("Hello World!");
});
app.listen(port);
前端:
const handleBooking = () => {
const newBooking = { ...loggedInUser, ...selectedDate };
fetch('http://localhost:5000/addBooking', {
method: 'POST',
header: { 'Content-Type' : 'application/json' },
body : JSON.stringify({newBooking})
})
.then((res) => res.json())
.then((data) => {
console.log(data);
});
};
有人能帮我吗?试着用下面的代码将它发送到你的前端 这需要使用 注意,由于使用了await,函数必须是async
异步函数bla(){}
你有没有检查过你是否到达了那个端点(/addBooking)?从来没有看到有人把
app。(…
放在连接的回调中。我只在我的mongo db中获取一个对象id。请求主体是空的。我对端点“/AdvAdvices”的错误我是新的,所以请考虑我的错误。
async function bla(){
const data = {newBooking};
const options = {
method: 'POST',
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data)
};
await fetch('/addBooking', options);
}
}