繁体   English   中英

node-fetch 发送 post 请求,正文为 x-www-form-urlencoded

[英]node-fetch send post request with body as x-www-form-urlencoded

我想使用带有以 x-www-form 编码的正文有效负载的 node-fetch 发送发布请求。 我尝试了这段代码,但不幸的是它不起作用:

paypalSignIn = function(){
var username = process.env.PAYPALID;
var password = process.env.PAYPALSECRET;
var authContent = 'Basic '+base64.encode(username + ":" + password);

fetch('https://api.sandbox.paypal.com/v1/oauth2/token', { method: 'POST',
 headers: {
       'Accept': 'application/json',
       'Accept-Language' :"en_US",
       'Authorization': authContent,
       'Content-Type': 'application/x-www-form-urlencoded'

  },
  body: 'grant_type=client_credentials' })
    .then(res => res.json()) // expecting a json response
    .then(json => console.log(json));

我不确定这种方式是否可行,但我需要将此标准用于模具 paypal api。 我收到状态码 400 错误

grant_type 是 null

谢谢

我不知道这是否是唯一的错误,但至少在单词Basic和编码的用户名/密码之间需要一个空格。

下次您提出问题时,还要发布您的脚本返回的内容。 我猜在这种情况下是 401 错误。

我今天使用了 PayPal 沙箱,这是我如何设法获得我的访问令牌和成功的响应(并回答了 OP 关于发送带有数据application/x-www-form-urlencoded POST 请求的问题)=>

我用node-fetch做到了,但是普通的 fetch API 应该是一样的。

import fetch from "node-fetch";

export interface PayPalBusinessAccessTokenResponseInterface {
    access_token: string;
}

export interface PayPalClientInterface {
    getBusinessAccessToken: (
        clientId: string, 
        clientSecret: string
    ) => Promise<PayPalBusinessAccessTokenResponseInterface>
}

const paypalClient: PayPalClientInterface = {
    async getBusinessAccessToken(
        clientId: string, 
        clientSecret: string
    ): Promise<PayPalBusinessAccessTokenResponseInterface> {
        const params = new URLSearchParams();
        params.append("grant_type", "client_credentials");
        const paypalAPICall = await fetch(
            "https://api-m.sandbox.paypal.com/v1/oauth2/token", 
            {
                method: "POST", 
                body: params,
                headers: {
                    "Authorization": `Basic ${Buffer.from(clientId + ":" + clientSecret).toString('base64')}`
                }
            }
        );
        const paypalAPIRes = await paypalAPICall.json();
        return paypalAPIRes;
    }
};

export default paypalClient;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM