[英]Send Array in post request using node.js using application/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.