我试图向其他本地服务器发布请求(因为在项目中我正在使用webpack,但我不知道如何管理默认的webpack服务器)。
这是我的发帖文件。
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))
})
这是我的服务器,当我单击按钮时,服务器登录{}的服务器中的控制台,而“ order_pizza”(我发布的变量)不为空。有什么问题,请帮助找到解决方法。
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)
答案 0 :(得分:1)
在前端,不要对主体进行字符串化处理,而是将其作为对象发送,如下所示。
还将目标端点更改为/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))
})
在您的服务器中,将端点URL更改为/post
,这样才有意义。
并按如下所示访问请求正文。
而且您不需要在此端点上使用urlencodedParser
app.post('/post', (req,res) => {
console.log(req.body)})
})
还可以将身体解析器应用于您的Express应用,如下所示
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
答案 1 :(得分:1)
尝试
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
您不必在app.post api调用中传递urlencodedParser,希望对您有所帮助