角度8 Http POST,内容类型为application / x-www-form-urlencoded

时间:2020-01-03 11:59:56

标签: http-post angular8 x-www-form-urlencoded

问这个问题似乎有点奇怪,但我不知道这一点。

我已经在Google和Google上通过stackoverflow链接进行了访问,实际上已经尝试了很多方法,但是我无法获得解决方案。以下是一些需要提及的内容

Angular 6 HTTP Client Post - Bad request

How to force Angular2 to POST using x-www-form-urlencoded

问题-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

谢谢

1 个答案:

答案 0 :(得分:2)

   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 })