如何在Node.js中实现curl -u选项

6

我正在尝试在Node中实现curl请求。在curl中,您可以执行以下POST请求:

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

我知道如何使用Node.js的http模块设置头部和编写数据有效负载,但是如何使用http模块实现-u client_id:client_secret


我认为这个答案描述了从服务器端的过程。https://dev59.com/6m025IYBdhLWcg3whWdm#5957629 - aembke
2个回答

3

目前我不会nodejs。但是由于你知道如何从nodejs设置Headers -H,我相信我现在可以帮助你了!-u client_id:client_secret 等价于以下内容:

-H "Authorization: Basic XXXXXXXXXXXXX"

这里的XXXXXXXXXXXXX是字符串client_id:client_secret的base64编码。不要忘记它们中间的:


0

curl -u 基于 base64 编码 "username:password" 字符串,并将结果附加为标头。

在 nodejs 中,只需将 auth 字段添加到 http.request 的选项中即可。

const req = http.request({
  hostname: "api.sandbox.paypal.com",
  path: "/v1/oauth2/token",
  auth: "client_id:client_secret",
  // ...

幕后,节点对字符串进行base64编码并添加格式化的头部。如果你使用另一个HTTP客户端,了解如何手动添加头部也可能会有帮助。
  1. 使用Buffer模块对你的"username:password"进行base64编码:
const credentials = Buffer.from("client_id:client_secret").toString("base64");
  1. 将base64编码的字符串作为头部添加,格式如下:
const req = http.request({
  hostname: "api.sandbox.paypal.com",
  path: "/v1/oauth2/token",
  headers: {
    Authorization: `Basic ${credentials}`
  // ...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接