javascript - 如何使用 node-fetch 模块模拟 curl 请求

标签 javascript node.js curl paypal paypal-sandbox

我有一个电子商务应用程序并试图联系 paypal rest api,特别是“paypal for partners”服务,我确实阅读了 Paypal Documentation一切都很好,但问题是他们提到了像这样使用 curl 的请求示例:

curl -v https://api.sandbox.paypal.com/v1/oauth2/token \
   -H "Accept: application/json" \
   -H "Accept-Language: en_US" \
   -u "client_id:secret" \
   -d "grant_type=client_credentials"

或者

使用具有基本身份验证的 postman :

  • 用户名:您的客户端 ID。

  • 密码:您的 secret 。

我正在尝试实现相同的东西,但使用来自 node.js 的 Node 获取

const fetch = require('node-fetch');

function authenticatePaypal() {
    fetch('https://api.sandbox.paypal.com/v1/oauth2/token', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'Accept-Language': 'en_US',
            'client_id': 'secret'
        },
        body: {
            "grant_type": "client_credentials"
        }
    }).then(reply => {
        console.log('success');
        console.log(reply);
    }).catch(err => {
        console.log('error');
        console.log(err);
    });
}

module.exports = {
    authenticatePaypal: authenticatePaypal
};

我收到 401 Unauthorized 的响应:

Response {
  size: 0,
  timeout: 0,
  [Symbol(Body internals)]:
   { body:
      PassThrough {
        _readableState: [ReadableState],
        readable: true,
        _events: [Object],
        _eventsCount: 2,
        _maxListeners: undefined,
        _writableState: [WritableState],
        writable: false,
        allowHalfOpen: true,
        _transformState: [Object] },
     disturbed: false,
     error: null },
  [Symbol(Response internals)]:
   { url: 'https://api.sandbox.paypal.com/v1/oauth2/token',
     status: 401,
     statusText: 'Unauthorized',
     headers: Headers { [Symbol(map)]: [Object] } } }

我尝试了 post man,它在 postman 中工作,我知道我的 Node 获取实现有问题,这是我第一次处理 json 格式的基本 Auth。

最佳答案

授权 header 错误。

-u "client_id:secret"

表示 curl 正在使用 Basic Authentication .

你应该添加授权 header

Authorization: Basic <base64 encoded "client_id:secret">

关于javascript - 如何使用 node-fetch 模块模拟 curl 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54420856/

相关文章:

bash - 用于代理和网页登录的 curl 命令

javascript - Angular js从输入文本框中删除前导和尾随空格

javascript - 从 HTML5/JS 中的 UWP 应用访问数据库

javascript - jquery 的 CORS 错误

mysql - 将数据存储在 MySQL block 中

javascript - 在 Node.js 中使用 axios 发布表单数据

javascript - 如何使用 AJAX 发送 div 元素?

javascript - cookie 中未设置 token

php - 使用 curl 和 api v3 在 Youtube 上上传视频

php - Wordpress wp_remote_post() 给出 "cURL error 6: Could not resolve host"