如何链接http.request()

时间:2019-08-02 19:23:05

标签: node.js http

我需要使用filters1(我不能使用其他库),并且我试图弄清楚如何将多个require('http')链接在一起?

在下面的示例中,我试图创建一个有4个人的家庭,每个人都有一个与之相关的宠物。我有3条路线将创建createFamily,createPerson和createPet。我也有方法http.request(),它将从每条路线的响应中获取ID,并将其沿链向下传递(家庭->人->宠物)。我不确定如何链接每个路由的响应并传递ID。

createHousehold()

1 个答案:

答案 0 :(得分:1)

例如,对于代理服务器,您可以将一个请求(可读)传送到另一个请求(可写)。

如果您只是在进行串行请求,则可以将它们包装在promise中,或者使用异步库。

"2.18.3"

并像这样使用它:

function createPet(personId) {

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

    const data = JSON.stringify({
        config: { personId }
    });

    const options = {
        host: 'myHost.com',
        port: '8080',
        path: '/v1/pet',
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Content-Length': data.length,
        },
    };

    const request = http.request(options, response => {
        let data = '';
        response.on('data', chunk => data += chunk);
        response.once('end', () => resolve(data));  // ! resolve promise here
    });

    request.once('error', err => {
       console.log('ERROR - createPet(): ', err.message || err);
       reject(err);  // ! if promise is not already resolved, then we can reject it here
    });

    request.write(data);
    request.end();

  });
}

如果要并行执行操作,请使用Promise.all()..或使用异步库。

对于播种数据库,我强烈建议async.autoInject,您将很快了解原因:

https://caolan.github.io/async/v2/docs.html#autoInject

您可以像这样使用它:

createHousehold(id)
.then(createFamily)
.then(createPerson)
.then(createPet);