nodejs - 如何宣传http.request?拒绝被叫两次

时间:2016-07-22 18:59:05

标签: node.js promise httprequest

我正在尝试将http.request包裹到Promise

 new Promise(function(resolve, reject) {
    var req = http.request({
        host: '127.0.0.1',
        port: 4000,
        method: 'GET',
        path: '/api/v1/service'
    }, function(res) {
        if (res.statusCode < 200 || res.statusCode >= 300) {
            // First reject
            reject(new Error('statusCode=' + res.statusCode));
            return;
        }
        var body = [];
        res.on('data', function(chunk) {
            body.push(chunk);
        });
        res.on('end', function() {
            try {
                body = JSON.parse(Buffer.concat(body).toString());
            } catch(e) {
                reject(e);
                return;
            }
            resolve(body);
        });
    });
    req.on('error', function(err) {
        // Second reject
        reject(err);
    });
    req.write('test');
}).then(function(data) {
    console.log(data);
}).catch(function(err) {
    console.log(err);
});

如果我从远程服务器收到错误的statusCode,则会在第二次拒绝之后调用首次拒绝。如何正确使它只调用单一拒绝(我认为首先拒绝在这种情况下是正确的)?我想我需要自己关闭res,但close()对象上没有ClientResponse方法。

UPD: 第二次拒绝很少发生 - 为什么?

6 个答案:

答案 0 :(得分:50)

你的代码几乎没问题。要重述一点,你需要一个用这个形式包装http.request的函数:

function httpRequest(params, postData) {
    return new Promise(function(resolve, reject) {
        var req = http.request(params, function(res) {
            // on bad status, reject
            // on response data, cumulate it
            // on end, parse and resolve
        });
        // on request error, reject
        // if there's post data, write it to the request
        // important: end the request req.end()
    });
}

请注意添加paramspostData,以便将其用作通用请求。 并注意OP代码中缺少必须始终调用的最后一行 req.end()

将这些夫妻变化应用于OP代码......

function httpRequest(params, postData) {
    return new Promise(function(resolve, reject) {
        var req = http.request(params, function(res) {
            // reject on bad status
            if (res.statusCode < 200 || res.statusCode >= 300) {
                return reject(new Error('statusCode=' + res.statusCode));
            }
            // cumulate data
            var body = [];
            res.on('data', function(chunk) {
                body.push(chunk);
            });
            // resolve on end
            res.on('end', function() {
                try {
                    body = JSON.parse(Buffer.concat(body).toString());
                } catch(e) {
                    reject(e);
                }
                resolve(body);
            });
        });
        // reject on request error
        req.on('error', function(err) {
            // This is not a "Second reject", just a different sort of failure
            reject(err);
        });
        if (postData) {
            req.write(postData);
        }
        // IMPORTANT
        req.end();
    });
}

这是未经测试的,但它应该可以正常工作......

var params = {
    host: '127.0.0.1',
    port: 4000,
    method: 'GET',
    path: '/api/v1/service'
};
// this is a get, so there's no post data

httpRequest(params).then(function(body) {
    console.log(body);
});

这些承诺也可以链接......

httpRequest(params).then(function(body) {
    console.log(body);
    return httpRequest(otherParams);
}).then(function(body) {
    console.log(body);
    // and so on
});

答案 1 :(得分:5)

还有其他方法,但是在这里您可以找到一种简单的方法将http.request设置为promise或async / await类型。

以下是有效的示例代码:

var http = require('http');

function requestAsync(name) {

    return new Promise((resolve, reject) => {
        var post_options = {
            host: 'restcountries.eu',
            port: '80',
            path: `/rest/v2/name/${name}`,
            method: 'GET',
            headers: {
                'Content-Type': 'application/json'
            }
        };
        let post_req = http.request(post_options, (res) => {
            res.setEncoding('utf8');
            res.on('data', (chunk) => {
                resolve(chunk);
            });
            res.on("error", (err) => {
                reject(err);
            });
        });
        post_req.write('test');
        post_req.end();
    });
}

//Calling request function
//:1- as promise
requestAsync("india").then(countryDetails => {
    console.log(countryDetails);
}).catch((err) => {
    console.log(err);  
}); 

//:2- as await
let countryDetails = await requestAsync("india");

答案 2 :(得分:2)

阅读所有这些和几篇文章后,我想我会发布一种处理 http 和 https 的“通用”解决方案:

const http = require("http");
const https = require("https");
const url_obj = require("url");

const request = async (url_string, method = "GET", postData = null) => {
  const url = url_obj.parse(url_string);
  const lib = url.protocol=="https:" ? https : http;
  const params = {
    method:method,
    host:url.host,
    port: url.port || url.protocol=="https:" ? 443 : 80,
    path: url.path || "/"
  };
  return new Promise((resolve, reject) => {
    const req = lib.request(params, res => {
      if (res.statusCode < 200 || res.statusCode >= 300) {
        return reject(new Error(`Status Code: ${res.statusCode}`));
      }
      const data = [];
      res.on("data", chunk => {
        data.push(chunk);
      });
      res.on("end", () => resolve(Buffer.concat(data).toString()));
    });
    req.on("error", reject);
    if (postData) {
      req.write(postData);
    }
    req.end();
  });
}

你可以这样使用:

request("google.com").then(res => console.log(res)).catch(err => console.log(err))

这在很大程度上受到 this article 的启发,但用内置的 api 替换了 hacky url 解析。

答案 3 :(得分:1)

我知道这个问题很旧,但是答案实际上激发了我编写轻量级承诺HTTP客户端的现代版本。这是一个新版本:

  • 使用最新的JavaScript语法
  • 验证输入
  • 支持多种方法
  • 易于扩展以获得HTTPS支持
  • 让客户决定如何处理响应代码
  • 还将让客户端决定如何处理非JSON主体

以下代码:

function httpRequest(method, url, body = null) {
    if (!['get', 'post', 'head'].includes(method)) {
        throw new Error(`Invalid method: ${method}`);
    }

    let urlObject;

    try {
        urlObject = new URL(url);
    } catch (error) {
        throw new Error(`Invalid url ${url}`);
    }

    if (body && method !== 'post') {
        throw new Error(`Invalid use of the body parameter while using the ${method.toUpperCase()} method.`);
    }

    let options = {
        method: method.toUpperCase(),
        hostname: urlObject.hostname,
        port: urlObject.port,
        path: urlObject.pathname
    };

    if (body) {
        options.headers['Content-Length'] = Buffer.byteLength(body);
    }

    return new Promise((resolve, reject) => {

        const clientRequest = http.request(options, incomingMessage => {

            // Response object.
            let response = {
                statusCode: incomingMessage.statusCode,
                headers: incomingMessage.headers,
                body: []
            };

            // Collect response body data.
            incomingMessage.on('data', chunk => {
                response.body.push(chunk);
            });

            // Resolve on end.
            incomingMessage.on('end', () => {
                if (response.body.length) {

                    response.body = response.body.join();

                    try {
                        response.body = JSON.parse(response.body);
                    } catch (error) {
                        // Silently fail if response is not JSON.
                    }
                }

                resolve(response);
            });
        });

        // Reject on request error.
        clientRequest.on('error', error => {
            reject(error);
        });

        // Write request body if present.
        if (body) {
            clientRequest.write(body);
        }

        // Close HTTP connection.
        clientRequest.end();
    });
}

答案 4 :(得分:-1)

使用bluebird api更容易,你可以promisify请求模块并使用请求函数async作为promise本身,或者你可以选择使用模块request-promise,这会让你没有工作创建一个promise但使用已经使用promise封装模块的对象,这是一个例子:

var rp = require('request-promise');

rp({host: '127.0.0.1',
    port: 4000,
    method: 'GET',
    path: '/api/v1/service'})
    .then(function (parsedBody) {
        // GET succeeded... 
    })
    .catch(function (err) {
        // GET failed... 
    });

答案 5 :(得分:-2)

希望获得帮助。

const request = require('request');

async function getRequest() {
  const options = {
    url: 'http://example.com',
    headers: {
      'Authorization': 'Bearer xxx'
    }
  };

  return new Promise((resolve, reject) => {
    return request(options, (error, response, body) => {
      if (!error && response.statusCode == 200) {
        const json = JSON.parse(body);
        return resolve(json);
      } else {
        return reject(error);
      }
    });
  })
}