[英]Why I'm getting empty object when doing post request
I tried to do post request to other localhost server(because in project I'm using webpack and I don't know how to manage default webpack server).我尝试向其他本地主机服务器发送请求(因为在项目中我使用的是 webpack 并且我不知道如何管理默认的 webpack 服务器)。
This is my post request file.这是我的发布请求文件。
btn_bag[0].addEventListener('click', (e) => {
e.preventDefault(),
fetch('http://localhost:3000/get', {
method:'POST',
headers: {
'Content-Type':'application/json;charset=utf-8'
},
body: JSON.stringify(order_pizza)
})
.then(console.log(order_pizza))
})
This is my server, when I click on button, console in server logged {}, when "order_pizza"(variable which I post) is not empty.这是我的服务器,当我单击按钮时,服务器中的控制台记录 {},当“order_pizza”(我发布的变量)不为空时。 What is the problem, help to find solution, please.
是什么问题,请帮忙寻找解决办法。
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const fs = require('fs');
const cors = require('cors');
const urlencodedParser = bodyParser.urlencoded({extended: false})
app.get('/', (req, res) => {
res.send('hello')
})
app.use(cors({
allowedOrigins: [
'http://localhost:9000'
]
}));
app.get('/get', (req,res) => {
console.log(req.body)
res.send('get')})
app.post('/get',urlencodedParser, (req,res) => {
console.log(req.body)})
app.listen(3000)
In your front-end, do not stringify the body, send it as an object like below.在您的前端,不要对正文进行字符串化,将其作为 object 发送,如下所示。 Change also the targetted end-point to
/post
还将目标端点更改为
/post
btn_bag[0].addEventListener('click', (e) => {
e.preventDefault(),
fetch('http://localhost:3000/post', {
method:'POST',
headers: {
'Content-Type':'application/json;charset=utf-8'
},
body: {order_pizza}
})
.then(console.log(order_pizza))
})
In your server, change the end-point URL to /post
so that it makes sense.在您的服务器中,将端点 URL 更改为
/post
以使其有意义。 And access the request body like below.并访问请求正文,如下所示。 And you do not need the
urlencodedParser
on this end-point而且您不需要在此端点上使用
urlencodedParser
app.post('/post', (req,res) => {
console.log(req.body)})
})
Also apply the body-parser to your express app like below还将正文解析器应用于您的快速应用程序,如下所示
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
try this尝试这个
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
you don't have to pass urlencodedParser in app.post api call, i hope it helps您不必在 app.post api 调用中传递 urlencodedParser,我希望它有所帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.