gpt4 book ai didi

javascript - 如何根据用户输入使用 Node.js 发出 HTTP 请求?

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

因此,我在 node.js 中启动了这个简单的项目,其中客户端发送一个 POST 请求,其中包含 Windows CMD 命令。

服务器接收 POST 请求,提取 CMD 命令,并在运行后以该命令的输出进行响应。

当我发出一个请求时,这种方法工作得很好,但后来我设置了一个系统来重复询问用户该命令,然后发送带有输入命令作为正文的 POST 请求。

以下是客户端代码:(不包括服务器端,因为它不相关)

var http = require("http");
var readline = require("readline");
var rl = readline.createInterface(process.stdin, process.stdout);

var options = {
hostname: "localhost",
port: 3001,
path: "/",
method: "POST",
headers: {
"Content-Type": "text/plain", // all command must be string
"Content-Length": 0 // changes based on what the command is
}
};

function requestCommand(hostname, port, command) {

// Some of the options of the request need to be changed based on
// what the command is
options.hostname = hostname;
options.port = port;
options.headers["Content-Length"] = command.length;

var req = http.request(options, function(res) {
console.log(`Got response. Status code: ${res.statusCode}`);

var resData = "";
res.setEncoding("utf-8");

res.on("data", function(chunk){
resData += chunk
});

res.on("end", function(){
return resData;
})

})

req.on("error", function (e){
return "\n\n\n ---------------\nERROR OCCURED IN THE REQUEST.\nREQUEST NOT SENT\n--------------" + e.stack;

})

req.write(command);
req.end();
}

rl.setPrompt("What command would you like to request from the server?: ");
rl.prompt();

rl.on("line", function(data){
if (data === "exit") {
console.log("\n\n\Exiting appplication...\n\n");
process.exit();
} else {
console.log("processing..");
var out = requestCommand("localhost", 3001, data);
console.log(`\n\n${out}\n\n`);
rl.prompt();
}
});

如果我在没有先创建服务器的情况下运行此命令,我不会收到错误消息,而是会收到 undefined

目前,我认为这是因为 requestCommand 函数在处理错误之前结束(在发出 error 事件并调用返回错误的回调函数之前),因为回调函数http.request 显然是异步的,在服务器响应或发出错误之前,函数结束,因此不返回任何内容 (undefined)

所以我的问题是:我可以保持该函数运行直到异步命令完成吗?

或者如果这是不可能的,是否有其他方法?当用户触发特定事件(例如数据输入)时,您将如何向该服务器发送请求?

编辑:我真的对使用第三方模块不感兴趣,因为我已经可以了。这个项目真的毫无意义,只是供我学习,所以我只使用核心模块。更具体地说,我只使用 HTTP 来发出请求(不是同步请求等)

最佳答案

requestCommand 必须返回一个由 resData 解析并在出现错误时被拒绝的 Promise:

 function requestCommand(hostname, port, command) {

return new Promise((resolve, reject) => { // immeadiately return a Promise that can be resolved/rejected later
// Some of the options of the request need to be changed based on
// what the command is
options.hostname = hostname;
options.port = port;
options.headers["Content-Length"] = command.length;

var req = http.request(options, function(res) {
console.log(`Got response. Status code: ${res.statusCode}`);

var resData = "";
res.setEncoding("utf-8");

res.on("data", function(chunk){
resData += chunk
});

res.on("end", function(){
resolve(resData); // resolve, return won't work here
});
});

req.on("error", function (e){
reject(e); // reject here, don't handle it
});

req.write(command);
req.end();
});
}

这样,您可以简单地使请求处理程序异步,然后等待函数调用:

rl.on("line", async function(data){ // make the function async so that we can work with promises more easily
if (data === "exit") {
console.log("\n\n\Exiting appplication...\n\n");
process.exit();
} else {
console.log("processing..");
try {
var out = await requestCommand("localhost", 3001, data); // "await" lets async code look like sync code, but it is still async
console.log(`\n\n${out}\n\n`);
} catch(e) { // the reject() call will end up here
console.log("invalid command " + e.stack); // handle here
}
rl.prompt();
}
});

关于javascript - 如何根据用户输入使用 Node.js 发出 HTTP 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52786088/

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