node.js - 如何将请求的输出存储在变量上?
问题描述
我有一个简单的 http 服务器,它根据从另一个请求返回的消息返回一条消息。
const http = require('http');
const app = new http.Server();
var message = 'm1';
const options = {
method: 'GET',
hostname: '<some-hostname>',
port: <some_port>
};
app.on('request', (rq, rs) => {
const m2req = http.request(options, (res) => {
res.on('data', (d) => {
message = d;
process.stdout.write(message);//this prints m2, which is correct
})
})
m2req.on('error', (error) => {
console.error(error)
})
m2req.end();
rs.writeHead(200, { 'Content-Type': 'text/plain' });
rs.write(message);// this should print 'm2' but prints 'm1'
rs.end('\n');
});
app.listen(<some_port>, () => {
});
什么是正确的方法让我的服务器打印 m2 而不是 m1?
感谢您的时间。
解决方案
在您的代码中,您正在请求另一个服务,这是一个异步操作。所以变量message
仍然是“m1”,因为在服务返回您res.write(message)
执行的值之前,它仍然是“m1”。你应该写res.send()
res.write()
res.writeHead
在回调里面res.on
const http = require('http');
const app = new http.Server();
var message = 'm1';
const options = {
method: 'GET',
hostname: '<some-hostname>',
port: <some_port>
};
app.on('request', (rq, rs) => {
const m2req = http.request(options, (res) => {
res.on('data', (d) => {
message = d;
process.stdout.write(message);//this prints m2, which is correct
rs.writeHead(200, { 'Content-Type': 'text/plain' });
rs.write(message);// this should print 'm2' but prints 'm1'
rs.end('\n');
})
})
m2req.on('error', (error) => {
console.error(error)
})
m2req.end();
});
app.listen(<some_port>, () => {
});
推荐阅读
- bash - $PATH 和 .bash_profile 的问题
- python - 将行转换为数组
- c++ - 这是带有 std::any 或 std::is_copy_constructible 的 libstdc++ 中的错误,还是合法错误?
- java - 尝试进行视频通话时出现以下错误。还添加了调试日志
- stanford-nlp - 如何使用/安装 StanfordCoreNLP 的语言模型?(英语-完整,英语-kbp)
- jenkins - 从 Jenkinsfile 中的共享库导入类
- thingsboard - Thingsboard:在一个 POST 中发送多个时间序列
- python-3.x - 错误:无法打开文件'worker':没有带有faust hello_world的文件或目录,例如
- eclipse - Tomcat 从终端运行,但不是从 Eclipse 和 Spring Tool Suite
- python - 如何将获取的文件名保存在 csv 中?