gpt4 book ai didi

javascript - 如何从 Node.js Express 中的 xhttp.send() 检索数据

转载 作者:行者123 更新时间:2023-12-03 00:03:24 26 4
gpt4 key购买 nike

所以我在首页有这一行:

var x = "Hi";
var y = 123;

xhttp.open("POST", "/toNodeServer", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");



xhttp.send(x, y);

在服务器中我有以下内容:

outer.post('/toNodeServer', function(req, res, next){

var x = req.body


console.log(x);

所以结果是它不发送 y 值,我从终端得到这个:{'嗨':''}

谁能解释一下发生了什么以及如何发送这两个变量?

最佳答案

<强> XMLHttpRequest.send(body) 仅采用 1 参数。

您需要发布 JSON 或发送 url 编码字符串(或任何其他序列化字符串)

JSON

xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send(JSON.stringify({ x: x, y: y}));

x-www-form-urlencoded

xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(`x=${x}&y=${y}`);

如果您发送 JSON,请不要忘记添加:

app.use(bodyParser.json());
app.use(bodyParser.urlencoded());

然后您将能够通过以下方式访问它:

const x = req.body.x;
const y = req.body.y;

或者使用解构:

const { x, y } = req.body;

关于javascript - 如何从 Node.js Express 中的 xhttp.send() 检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55082385/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com