當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript http.request函數代碼示例

本文整理匯總了TypeScript中http.request函數的典型用法代碼示例。如果您正苦於以下問題:TypeScript request函數的具體用法?TypeScript request怎麽用?TypeScript request使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了request函數的9個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。

示例1:

(() => {
    const tunnelingAgent = tunnel.httpOverHttps({
        maxSockets: poolSize, // Defaults to http.Agent.defaultMaxSockets

        proxy: { // Proxy settings
            host: proxyHost, // Defaults to 'localhost'
            port: proxyPort, // Defaults to 443
            localAddress, // Local interface if necessary

            // Basic authorization for proxy server if necessary
            proxyAuth: 'user:password',

            // Header fields for proxy server if necessary
            headers: {
                'User-Agent': 'Node'
            },

            // CA for proxy server if necessary
            ca: [ fs.readFileSync('origin-server-ca.pem')],

            // Server name for verification if necessary
            servername: 'example.com',

            // Client certification for proxy server if necessary
            key: fs.readFileSync('origin-server-key.pem'),
            cert: fs.readFileSync('origin-server-cert.pem'),
        }
    });

    const req = http.request({
        host: 'example.com',
        port: 80,
        agent: tunnelingAgent
    });
})();
開發者ID:AbraaoAlves,項目名稱:DefinitelyTyped,代碼行數:35,代碼來源:tunnel-tests.ts

示例2: Promise

 await new Promise((resolve) => {
   const reqData = "name is sparky";
   const req = request(
     {
       socketPath: runtime.metadata.socketPath,
       path: "/",
       method: "post",
       headers: {
         "Content-Type": "gibber/ish",
         "Content-Length": reqData.length,
       },
     },
     (res) => {
       let data = "";
       res.on("data", (chunk) => (data += chunk));
       res.on("end", () => {
         expect(JSON.parse(data).type).to.deep.equal("Buffer");
         expect(JSON.parse(data).data.length).to.deep.equal(14);
         resolve();
       });
     }
   );
   req.write(reqData);
   req.end();
 });
開發者ID:firebase,項目名稱:firebase-tools,代碼行數:25,代碼來源:functionsEmulatorRuntime.spec.ts

示例3:

 process.on("exit", () => {
     http.request({
         port: 3001,
         path: "/" + name,
         method: "DELETE"
     }).end();
 });
開發者ID:herrmanno,項目名稱:proxy,代碼行數:7,代碼來源:client.ts

示例4: Headers

      ngZome.run(() => {

        nodeReq = http.request(reqInfo, (res: http.IncomingMessage) => {
          let body = '';
          res.on('data', (chunk) => body += chunk);

          let status = res.statusCode;
          let headers = new Headers(res.headers);
          let url = res.url;

          res.on('end', () => {
            let responseOptions = new ResponseOptions({body, status, headers, url});
            let response = new Response(responseOptions);

            if (utils.isSuccess(status)) {
              ngZome.run(() => {
                responseObserver.next(response);
              });
              ngZome.run(() => {
                responseObserver.complete();
              });
              return;
            }
            ngZome.run(() => {
              responseObserver.error(response);
            });
          });
        });
      })
開發者ID:ldenman,項目名稱:universal,代碼行數:29,代碼來源:node_http.ts

示例5: checkWebsiteIsRunning

function checkWebsiteIsRunning() {

    //The url we want is: 'www.random.org/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
    const options: http.RequestOptions = {
        host: 'localhost',
        port: 4200,
        path: '/'
    };

    const callback = function (response: http.IncomingMessage) {
        let content = '';

        //another chunk of data has been recieved, so append it to `str`
        response.on('data', function (chunk) {
            content += chunk;
        });

        //the whole response has been recieved, so we just print it out here
        response.on('end', function () {
            if (content.indexOf('<title>Croquet Australia Admin Website</title>') < 0) {
                console.log('Website content does not include expected title');
                console.log(content);
                throw new Error('Website is not running');
            }
            console.log('Website is running');
        });
    }

    http.request(options, callback).end();
}
開發者ID:croquet-australia,項目名稱:croquet-australia-admin-website,代碼行數:30,代碼來源:configure-iis.ts

示例6: sender

    public static sender(payload: string, config) {
        var headers = {
            'Content-Type': 'application/json',
            'Content-Length': payload.length,
        };

        var endpointUrl = config.endpointUrl();
        if (endpointUrl && endpointUrl.indexOf("//") === 0) {
            // add http protocol if the config did not specify https
            endpointUrl = "http:" + endpointUrl;
        }

        var options = {
            host: url.parse(endpointUrl).hostname,
            path: url.parse(endpointUrl).pathname,
            method: 'POST',
            headers: headers
        };

        var req = http.request(options, (res) => {
            res.setEncoding('utf-8');

            //returns empty if the data is accepted
            var responseString = '';
            res.on('data', (data) => {
                responseString += data;
            });
            res.on('end', () => {
            });
        });

        req.write(payload);
        req.end();
    }
開發者ID:UIKit0,項目名稱:AppInsights-node.js,代碼行數:34,代碼來源:Sender.ts

示例7: _getNpmPackageJson

/**
 * Get the NPM repository's package.json for a package. This is p
 * @param {string} packageName The package name to fetch.
 * @param {LoggerApi} logger A logger instance to log debug information.
 * @returns {Observable<JsonObject>} An observable that will put the pacakge.json content.
 * @private
 */
function _getNpmPackageJson(
  packageName: string,
  logger: logging.LoggerApi,
): Observable<JsonObject> {
  const url = `http://registry.npmjs.org/${packageName.replace(/\//g, '%2F')}`;
  logger.debug(`Getting package.json from ${JSON.stringify(packageName)}...`);

  let maybeRequest = npmPackageJsonCache.get(url);
  if (!maybeRequest) {
    const subject = new ReplaySubject<JsonObject>(1);

    const request = http.request(url, response => {
      let data = '';
      response.on('data', chunk => data += chunk);
      response.on('end', () => {
        try {
          const json = JSON.parse(data);
          subject.next(json as JsonObject);
          subject.complete();
        } catch (err) {
          subject.error(err);
        }
      });
      response.on('error', err => subject.error(err));
    });
    request.end();

    maybeRequest = subject.asObservable();
    npmPackageJsonCache.set(url, maybeRequest);
  }

  return maybeRequest;
}
開發者ID:iwe7,項目名稱:devkit,代碼行數:40,代碼來源:npm.ts

示例8: reject

  return new Promise<string>((resolve, reject) => {
    let unexpectedEnd = () => {
      reject({code: 'UNKNOWN', message: 'Request ended unexpectedly'});
    };
    let req = http.request(
        {port: parseInt(port), method: method, path: path, headers: headers}, (res) => {
          req.removeListener('end', unexpectedEnd);
          if (res.statusCode !== 200) {
            reject({code: res.statusCode, message: res.statusMessage});
          } else {
            let buffer: (string|Buffer)[] = [];
            res.on('data', buffer.push.bind(buffer));
            res.on('end', () => {
              resolve(buffer.join('').replace(/\0/g, ''));
            });
          }
        });

    if (timeout) {
      req.setTimeout(timeout, () => {
        reject({code: 'TIMEOUT', message: 'Request timed out'});
      });
    }
    req.on('error', reject);
    req.on('end', unexpectedEnd);

    if (hasContent) {
      req.write(data as string);
    }

    req.end();
  });
開發者ID:sjelin,項目名稱:webdriver-manager,代碼行數:32,代碼來源:utils.ts

示例9: reject

            worker.request = new Promise<PhantomResult>((resolve, reject) => {
                const hmac = crypto.createHmac("sha256", worker.key)
                    .update([worker.counter, 'POST', '/', `localhost:${worker.port}`, 'application/json', payload].join('\n'))
                    .digest('hex');

                http.request({
                    port:    worker.port,
                    method:  'POST',
                    auth:    worker.counter + ':' + hmac,
                    headers: {
                        'Content-Type':   'application/json',
                        'Content-Length': payload.length,
                    },
                }, (response) => {
                    let result = '';

                    response.on('error', (error) => {
                        reject(error);
                    });

                    response.on('data', (data) => {
                        result += data;
                    });

                    response.on('end', () => {
                        resolve([response, result]);
                    });
                })
                .on('error', (error) => {
                    reject(error);
                })
                .end(payload);
            });
開發者ID:LeviticusMB,項目名稱:ghostly,代碼行數:33,代碼來源:ghostly.ts


注:本文中的http.request函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。