如何使用post方法在Node.js中调用API?

时间:2018-06-22 11:25:12

标签: node.js

我有一个使用curling API的PHP代码示例。如何在Nodejs中卷曲它?

<?php
$apiKey = "Your API Key Goes Here";
$payUrl = "https://example.com/api/requery/";
$data['apiKey'] = $apiKey;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $payUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$r = curl_exec($ch);
curl_close($ch);
var_dump($r);
?>

1 个答案:

答案 0 :(得分:1)

使用节点中包含的https软件包将您的请求发送到API

const https = require('https');

const options = {
  hostname: 'encrypted.google.com',
  port: 443,
  path: '/',
  method: 'GET'
};

const req = https.request(options, (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.on('data', (d) => {
    process.stdout.write(d);
  });
});

req.on('error', (e) => {
  console.error(e);
});
req.end();