首页 > 解决方案 > 如何将请求的输出存储在变量上?

问题描述

我有一个简单的 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?

感谢您的时间。

标签: node.js

解决方案


在您的代码中,您正在请求另一个服务,这是一个异步操作。所以变量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>, () => {
});

推荐阅读