首页 > 解决方案 > angular 8 Http POST,内容类型为 application/x-www-form-urlencoded

问题描述

问这个问题似乎有点奇怪,但我想不通。

我已经通过这个和谷歌上的stackoverflow链接,实际上尝试了很多东西,但我无法解决这个问题。下面是一些需要提及的

Angular 6 HTTP 客户端发布 - 错误请求

如何使用 x-www-form-urlencoded 强制 Angular2 发布

问题 - api 的请求选项始终为 400(错误请求)

洞察力 -

下面是正在处理另一个项目的代码

  const headers = new HttpHeaders({
    'Content-Type': 'application/x-www-form-urlencoded'
  });
  const body = new HttpParams()
    .set('grant_type', 'password')
    .set('username', stateData.username)
    .set('password', stateData.password)
    .set('client_id', 'XXXXX-5B3C-4A7D-WEW-23BWWWF9B7872'); //Letters are dummy here for security reasons

//URL preceded by https
return this.http.post('abc.com/authtoken', body , {headers: headers }).pipe(
  map(res => {
    return res;
  })
 );

现在,当我在另一个项目中尝试相同的代码时,它没有通过 OPTIONS 请求,抛出 400(错误请求)。

我们可以假设其余的东西是为了完成这项工作。问题主要出在代码片段中。

最令人惊奇的是,当我在 url 中添加一个斜杠(如 - authtoken/ )时,它似乎通过了 OPTIONS 200OK 但在原始 POST 请求中失败为 404,这是可以理解的,因为 authtoken/ 不存在。

有什么办法可以通过。我有点困惑要做什么。

如前所述,我已经尝试了很多方法来使它工作。请建议

我们正在使用 Angular 8.2.13

谢谢

标签: http-postangular8x-www-form-urlencoded

解决方案


   const headers = new HttpHeaders().set(
     'Content-Type',
    'application/x-www-form-urlencoded;'
   );

   body = 'grant_type=' + password + '&username=' + setData.username + '&password=' + 
   setData.password + '&Client_Id=' + 'XXXXX-5B3C-4A7D-WEW-23BWWWF9B7872';

   return this.http.post('abc.com/authtoken', body , {headers: headers })

推荐阅读