如何在 Angular post 调用中正确发送 application/x-www-form-urlencoded

How to correctly send application/x-www-form-urlencoded in Angular post call

我正在尝试获取 Paypal 访问令牌,根据 paypal,请求的数据是 -d "grant_type=client_credentials" 并且必须以 application/x-www-form-urlencoded 格式发送,下面是我的代码现在正在尝试

let body = "grant_type=client_credentials"

return this.httpClient.post<any (`https://api.sandbox.paypal.com/v1/oauth2/token`,body);

我正在像下面这样在 auth 拦截器中设置 header

const copiedReq = req.clone({ 
    setHeaders: {
      'Authorization': `Basic  ${this.client_id}:${this.secrete}`, 
      'Accept': 'application/json',
      'Content-Type':'application/x-www-form-urlencoded',
    }
});
return next.handle(copiedReq); 

它总是返回 401 Unauthorized 但我的 client_idsecrete 没问题,因为当我尝试与邮递员通话时它工作正常

网络选项卡

它在具有相同凭证的邮递员身上工作正常,但在这里不行,我做错了什么?我怎样才能做出正确的请求来获得结果

Paypal 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"

迟到总比不到好。我刚刚遇到了和你一样的问题,我终于解决了。 您必须对凭据进行 base 64 编码:

let credentials: btoa(`${this.client_id}:${this.secrete}`);

const copiedReq = req.clone({ 
setHeaders: {
  'Authorization': `Basic  `+credentials, 
  'Accept': 'application/json',
  'Content-Type':'application/x-www-form-urlencoded',
}
});
return next.handle(copiedReq); 

几分钟前这对我有用。希望下次对你有用:D