【问题标题】:How do I pass user name and password in an http post request from angular 4如何在 Angular 4 的 http post 请求中传递用户名和密码
【发布时间】:2017-08-09 10:25:10
【问题描述】:

我需要使用 Angular http post 请求将用户名和密码发送到登录 api。这是我的代码:

const params = new URLSearchParams();
    params.set('username', username);
    params.set('password', password);
    this.headers = new Headers({ 'content-type': 'application/x-www-form-urlencoded', 'authorization': 'Basic' });
    this.options = new RequestOptions({headers: this.headers, method: RequestMethod.Post, params: params });
    return this.http.post(this.config.baseUrlAuthSvc + this.config.login, this.options)
        .map((response) => { return response; })

我收到以下错误响应:

请求网址:http://111.22.333.44:55/api/token 请求方法:选项 状态码:400 错误请求 远程地址:172.31.131.13:85 推荐人政策:降级时不推荐人

我错过了什么吗?

【问题讨论】:

  • 您可能需要将请求正文设置为username=enteredUsername&password=enteredPassword
  • @jason 是的,我就是这么做的。获取请求中应使用参数

标签: angular api http


【解决方案1】:

你可以试试这个方法

return $http.post(URL, data, {
        headers: {
            "Content-Type": "application/x-www-form-urlencoded"
        }
    }).success(function (response) {
        return response;
    });

data 是输入参数,例如如下

var data = "username=" + username + "password=" + password;

【讨论】:

  • 我错过了 angular 4,这个答案在 1.x 版本的情况下会有帮助
【解决方案2】:

显然,在 post 请求中,不可能在 requestoptions 中传递参数。 http.post 请求中的第二个参数是 body,所以我将字符串 'username=xyz&password=123' 作为第二个参数传递,它工作正常。

关键是,如果是 http post 请求,请不要使用参数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-14
    • 2017-11-27
    • 2015-02-15
    • 2016-08-16
    • 2015-05-28
    • 2019-03-20
    相关资源
    最近更新 更多