使用x-www-form-urlencoded的HttpClient POST请求 [英] HttpClient POST request using x-www-form-urlencoded

查看:839
本文介绍了使用x-www-form-urlencoded的HttpClient POST请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用x-www-form-urlencoded content type标头发出POST请求,如下所示:

I'm trying to make a POST request with x-www-form-urlencodedcontent type header as follows:

login(username, password): Observable<any> {
    return this.http.post('/login', {
      username: username,
      password: password
      },
      {
        headers: new HttpHeaders()
          .set('Content-Type', 'x-www-form-urlencoded')
      }
      );

不幸的是,我的API说我发送了空的用户名和密码.

Unfortunately my API says that I sent empty username and password.

所以我决定向我的登录端点发出一个邮递员请求,并查看问题的根源,并且邮递员请求确实返回了用户名和密码.

so I decided to make a postman request to my login endpoint and see where the problem comes from, and the postman request did return the username and password.

当我从邮递员发布我的API时,返回我的用户名和密码,而当我从Angular应用中发布时,我的API返回空值又是怎么回事?我有什么想念的吗?

How comes that when I'm posting from postman my API return my username and password and when I post from my Angular app my API returns empty values? Is there anything I'm missing?

推荐答案

您正在将JSON数据而不是表单数据发布到API. 下面的代码段应该可以使用.

You're posting JSON data to the API instead of form data. The snippet below should work.

login(username, password): Observable<any> {
  const body = new HttpParams()
    .set('username', username)
    .set('password', password);

  return this.http.post('/login',
    body.toString(),
    {
      headers: new HttpHeaders()
        .set('Content-Type', 'application/x-www-form-urlencoded')
    }
  );
}

这篇关于使用x-www-form-urlencoded的HttpClient POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆