簡體   English   中英

如何通過 res.send 或 res.jsonn 從回調內部的響應中以快遞方式傳遞響應正文?

[英]How to pass response body via res.send or res.jsonn in express from response inside callback?

我是 expressjs 的新手,想問一個問題,如何將回調響應中的正文塊/數據傳遞到 res.send() 或 res.json()。 這是我的代碼:

app.get('/search', function(req, res, next) {
const httpOptions = {
        hostname: '...com.sg',
        port: 443,
        path: '...',
        method: 'get',
        headers: {
            Authorization: Signatures ,
            ApiKey: '...',
            ApiSecret: '...',
            FINS: fins      
        }  
    }
    console.log(`statusCode: ${res.statusCode}`)
    console.log('headers:', httpOptions.headers);
    const callback = function(response) {

        response.on('data', function (chunk) {
            console.log(`statusCode: ${response.statusCode}`)
            console.log('Body: ' + chunk);     
        });

        response.on('end', function () {

        });
      }

     var req = https.request(httpOptions, callback).end();


res.send(req.body);
// res.end(JSON.stringify(req.body, null, 2))

next()

});

當我簽入控制台時,它似乎還可以,並給我回復,就像我想要的那樣:

Body: {"status":"Ok","workPassEntries":[{"fin":"F.......A","status":"ObjectNotFound","workPass":null}]}

但另一方面,在瀏覽器和 postman 中給我空的身體,對於令人困惑的問題表示歉意,因為我是新手,在此先感謝。

您需要在回調 function 中調用res.send()

app.get('/search', function(req, res, next) {
const httpOptions = {
        hostname: '...com.sg',
        port: 443,
        path: '...',
        method: 'get',
        headers: {
            Authorization: Signatures ,
            ApiKey: '...',
            ApiSecret: '...',
            FINS: fins      
        }  
    }
    console.log(`statusCode: ${res.statusCode}`)
    console.log('headers:', httpOptions.headers);
    const callback = function(response) {

        response.on('data', function (chunk) {
            console.log(`statusCode: ${response.statusCode}`)
            console.log('Body: ' + chunk);
            //Here you can send the stream of data to client side
            res.send(chunk);    
        });

        response.on('end', function () {

        });
      }

     var req = https.request(httpOptions, callback).end();

next()

});

現在它解決了:直接請求使用此代碼:

let data = '';

  let apiRequest = https.request( options, function(res) {
    console.log("Connected");

    res.on("data", chunk => {     
      data += chunk;
      console.log('Body: ' + chunk);
    });

    res.on("end", () => {
      console.log("Data Verified");
      console.log(`statusCode: ${res.statusCode}`)
      response.end(data);

    });
  });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM