您的ajax请求没有发布任何数据,因此req.body为空。此外,req.body.ip和req.body.port不会自动包含,因此您必须将它们与响应一起发送。要获取主机和IP,请参阅此JSFiddle。您可以使用表单获取值,使用函数自己创建它们,甚至可以硬编码它们,但必须使用ajax请求发送它们。尝试格式化您的要求是这样的:
$(function() {
$('#loadRequest').click(function() {
$.post('/output2', {
number: 42, //post a hard coded value
host: someVar, //post the value from a variable you create
ip: $('#someInput').val() //post the value from a input
}, function(res) {
$('#val').text(res);
});
});
})
更新:
从这个SPO question:主机名是你机器的名称和域名的组合(例如计算机名。 domain.com)。主机名称的目的是可读性 - 比IP地址更容易记忆。所有主机名解析为IP地址,因此在许多情况下,他们都被称为可互换。
数字是无论用作数字的值。如果没有必要发送任何数据,您实际上不需要发送任何数据,您可以使用空对象{}(尽管如果情况如此,那么您应该使用get请求)。我不知道为什么你想要主机和IP,我将它们包含在你的原始代码中,我认为它们被用于未包含在代码段中的内容。如果你不需要他们,他们不是必需的。
你不需要把钥匙变成字符串,但它不会伤害任何东西。 'number'和number都可以使用。他们只是成为您的req.body中的钥匙,其他钥匙将返回undefined。在你req.body上面的例子会是这样一个对象:
{
number: 42,
host: theValueOfSomeVar, //if you send a variable it sends the value, not the variable itself
ip: theValueOf$('#someInput').val()
} 在你的路线
然后req.body.number === 42,req.body.host === theValueOfSomeVar,req.body.ip === theValueOf$('#someInput').val()和req.body.anyOtherKey === undefined
我不是100%肯定这将工作,但我认为是这样...而不是渲染数据并发送每条消息,进行30次调用并将每条消息推送到数组中,然后将数组发送到前端,并使用jQuery在成功回调中每10秒添加一条消息。
新新的Node.js代码(与client.on):
app.post('/output2', function(req, res) {
let HOST = 192.168.0.136;
let PORT = 69;
//Reading in the user's command, converting to hex
let message = Buffer.from(42, 'hex'); //new Buffer(str[, encoding]) is deprecated
//Sends packets to TFTP
client.send(message, 0, message.length, PORT, HOST, function(err, bytes) {
if (err) throw err;
});
client.on('message', function(message) {
let msg = new Buffer(message, 'hex');
res.send(msg);
});
});
新新的jQuery:
$(function() {
$('#loadRequest').click(function() {
var count = 0;
var requestLoop = setInterval(function() {
$.post('/output2', {
number: 42, //post a hard coded value
host: someVar, //post the value from a variable you create
ip: $('#someInput').val() //post the value from a input
}, function(res) {
$('#val').append(res);
});
count++;
if (count >= 30) {
clearInterval(requestLoop);
}
}, 10000);
});
})