【问题标题】:What will be the nodejs equivalent of PHP curl code [duplicate]PHP curl代码的nodejs等价物将是什么[重复]
【发布时间】:2020-12-08 23:53:29
【问题描述】:

这可能看起来很傻,但我正在尝试从 API (WHMCS) 获取一些数据。在文档中,他们有这样的代码:

// Call the API 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $whmcsUrl . 'includes/api.php'); 
curl_setopt($ch, CURLOPT_POST, 1); 
curl_setopt($ch, CURLOPT_TIMEOUT, 30); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1); 
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2); 
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postfields)); 
$response = curl_exec($ch); 
if (curl_error($ch)) { 
die('Unable to connect: ' . curl_errno($ch) . ' - ' . curl_error($ch)); 
} 
curl_close($ch); 
 
// Decode response 
$jsonData = json_decode($response, true); 
 
// Dump array structure for inspection 
var_dump($jsonData); 

我使用 axios 在 nodejs 中编写了代码,目的是做同样的事情:

axios.get(whmcsUrl + `includes/api.php?accesskey=${apiAccessKey}`, postFields)
.then(res => console.log(res))
.catch(err => console.log(err))

对 PHP 或 Node 没有深入的了解,请帮助!我在节点中执行此请求时收到403 Forbidden?我做错了什么。

更新:我现在不是传递对象 (postFields),而是在 url 本身中传递用户名或密码之类的东西:

axios.post(whmcsUrl + `includes/api.php?action=${apiAction}&username=${apiIdentifier}&password=${apiSecret}&accesskey=${apiAccessKey}&responsetype=json`)
.then(res => console.log(res))
.catch(err => console.log(err))

它仍然给我403 Forbidden 错误。

【问题讨论】:

  • 您是在进行 GET 还是 POST?对于 axios,您正在执行 GET,但 PHP 您正在执行 POST
  • @AndrewNolan 我在 get 和 post 调用中都遇到了同样的错误

标签: php node.js curl axios


【解决方案1】:

CURLOPT_POSTFIELDS, http_build_query($postfields) 的 axios 等效项是双重的 - 首先将参数字符串化并将它们作为帖子正文传递,然后将 application/x-www-form-urlencoded 指定为标题中的内容类型。

类似这样的:

const axios = require('axios')
const qs = require('qs')

const data = qs.stringify(postFieldsObject)
const config = {
  method: 'post',
  url: `${whmcsUrl}includes/api.php`,
  headers: { 
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  data : data
}

axios(config)
.then(function (response) {
  console.log(JSON.stringify(response.data))
})
.catch(function (error) {
  console.log(error)
})

【讨论】:

  • 谢谢!这可以在没有qs 包的情况下完成吗?我不再使用节点了。
  • 是的'qs.stringify'。您也可以轻松地手动构建它。关键是这个字符串是 POST 数据而不是 URL 的一部分,其次必须传递正确的内容类型标头。
猜你喜欢
  • 2018-10-24
  • 1970-01-01
  • 1970-01-01
  • 2012-10-22
  • 1970-01-01
  • 1970-01-01
  • 2012-04-15
  • 2016-08-14
  • 2012-06-03
相关资源
最近更新 更多