[英]node-fetch send post request with body as x-www-form-urlencoded
i want to send a post request using node-fetch with a body payload encoded in the x-www-form.我想使用带有以 x-www-form 编码的正文有效负载的 node-fetch 发送发布请求。 I tried this code but unfortunately it doesnt work:我尝试了这段代码,但不幸的是它不起作用:
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));
} I'm not sure if this way is possible but i need to use this standard for die paypal api.我不确定这种方式是否可行,但我需要将此标准用于模具 paypal api。 I'm getting statu code 400 with error我收到状态码 400 错误
grant_type is null grant_type 是 null
Thx谢谢
I don't know if this is the only error, but at the very least you need a space between the word Basic
and the encoded username/password.我不知道这是否是唯一的错误,但至少在单词Basic
和编码的用户名/密码之间需要一个空格。
Next time you ask a question, also post what your script returned.下次您提出问题时,还要发布您的脚本返回的内容。 I'm guessing it was a 401 error in this case.我猜在这种情况下是 401 错误。
I used the PayPal sandbox today, here is how I managed to get my access token and a successful response (and also answering the OP's question about sending application/x-www-form-urlencoded
POST requests with data) =>我今天使用了 PayPal 沙箱,这是我如何设法获得我的访问令牌和成功的响应(并回答了 OP 关于发送带有数据application/x-www-form-urlencoded
POST 请求的问题)=>
I did it with node-fetch
but the plain fetch API should work the same.我用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.