[英]node.js and express : how to wait for udp response
我在這里學習一點node.js編程並遇到了問題。
當express獲取POST請求時,它應該使用dgram模塊通過UDP進行radius驗證。 Radius身份驗證的響應稍后會出現,但POST請求回調已經退出,req和res變量將丟失,並且無法使用相同的TCP連接進行響應。
如果我應該等待半徑響應(這是非常快)我應該如何在node.js和express中等待?
下面的代碼執行基本的POST處理和radius驗證。
非常感謝您的任何提示。
var http = require('http'); var express = require('express'); var bodyParser = require('body-parser'); var radius = require('radius'); var dgram = require('dgram'); var radius_secret = 'really_secret'; var radius_server = '127.0.0.1'; var radius_port = '1812'; function handleAuthentication(req, res) { console.log("BODY:",req.body); var client = dgram.createSocket("udp4"); var account = req.body.account; var password = req.body.password; var packet = { code: 'Access-Request', secret: radius_secret, identifier: 0, attributes: [ ['NAS-IP-Address', radius_server], ['User-Name', account + "@exampledomain.something"], ['User-Password', password] ] }; client.on('error', function(e) { throw e; }); client.on('message', function(msg, rinfo) { var radius_response = radius.decode({packet: msg, secret: radius_secret}); console.log(radius_response); }); var encoded = radius.encode(packet); client.send(encoded, 0, encoded.length, radius_port, radius_server); } var app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false})); app.post('/authenticate', function(req, res) { // Authenticate against radius server handleAuthentication(req, res); // The radius response is not received yet, and we will exit the post request // here and loose the req and res. }); var server = http.createServer(app); server.listen(80);
您需要在client
回調中進行響應。 因此,例如,在消息后回復:
client.on('message', function(msg, rinfo) {
var radius_response = radius.decode({packet: msg, secret: radius_secret});
console.log(radius_response);
res.send('somethingCalculatedWithUDPResponse');
});
你應該在error
回調中類似地處理它。
當函數結束時, res
和req
不會“死”,它們仍然可以被作為回調傳遞的閉包引用。
如果您無法在handleAuthentication
函數中使用res
,或者為了某些代碼設計目的而不想響應客戶端,則可以使用新的JS async / await函數。
app.post('/authenticate', async function(req, res) {
// Authenticate against radius server
try{
let udpResponse = await handleAuthentication(req, res);
} catch (error){
// handle error. use 'res' to notify about error
}
// if ok
res.send("your response")
//or better
res.send(udpResponse)
});
並在功能內:
client.on('message', function(msg, rinfo) {
var radius_response = radius.decode({packet: msg, secret: radius_secret});
return radius_response;
});
Async / await會將函數包裝到promise中,並且return語句將在后台轉換為解析/拒絕,然后您可以在函數外部執行任何操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.