【问题标题】:How to add headers to my Angular post request?如何将标头添加到我的 Angular 发布请求中?
【发布时间】:2019-08-16 16:00:57
【问题描述】:

对于一个学校项目,我需要使用 Angular 制作一个简单的登录页面。单击登录按钮时,我需要在我的帖子中添加一个授权标题。我创建了一个后端,当我使用邮递员将我的授权值发布到该后端时,它可以正常工作,因此后端没有任何问题。当我尝试使用我的前端发布到同一个后端时,它不起作用。在帖子中添加标题的最佳方法是什么?看来意见分歧了。这是我的代码:

export class LoginComponent{
    title = 'Login';
    email = '';
    password = '';
    credentials = '';
    basic = '';
    constructor(private http:HttpClient){

    }

    createAuthorizationHeader(headers:Headers,basic){
        headers.append('Authorization',basic);
    }

    login(event){
        this.email = (<HTMLInputElement>document.getElementById("email")).value;
        this.password = (<HTMLInputElement>document.getElementById("password")).value;
        this.credentials = this.email + ":" + this.password;
        this.basic = "Basic " + btoa(this.credentials);
        console.log(this.basic);
        let headers = new Headers();
        headers.append('Content-Type','application/json');
        headers.append('Authorization',this.basic);
        let options = new RequestOptions({headers:headers});
        console.log(headers);
        return this.http.post('http://localhost:8000/api/v1/authenticate',options)
        .subscribe(
            res =>{
                console.log(res);
            },
            err => {
                console.log(err.message);
            }
        )
    }
}

当我运行该代码时,我得到一个 400 状态响应并且没有添加标头。

【问题讨论】:

标签: angular typescript angular-httpclient


【解决方案1】:

传递给HttpClient.post 的第二个参数表示请求的正文,但您在此处提供Headers。使用以下方法正确提供标题:

return this.http.post('http://localhost:8000/api/v1/authenticate', null, options);

我在正文示例中显示了null,但您可能希望它以某种形式包含emailpassword 属性。

您还混合了HttpHttpClient。如果您打算使用HttpClient(现在是推荐的方法),请放弃RequestOptionsHeaders 以支持HttpHeaders。这变成:

let headers = new HttpHeaders({
    'Content-Type': 'application/json',
    'Authorization': this.basic });
let options = { headers: headers };

其余代码保持不变。您的createAuthorizationHeader 函数需要使用并返回HttpHeaders 的实例。这个类是不可变的,所以append 每次调用它都会返回一个新对象。从@angular/common/http 导入HttpHeaders

【讨论】:

    【解决方案2】:

    这可能对你有帮助

    let headers = new Headers();
    headers.append('Content-Type','application/json');
    //post data missing(here you pass email and password)
    data= {
    "email":email,
    "password":password
    }
    return this.http.post('http://localhost:8000/api/v1/authenticate',data,{ headers: headers})
        .subscribe(
            res =>{
                console.log(res);
            },
            err => {
                console.log(err.message);
            }
        )
    

    【讨论】:

    • 感谢您的快速回复,但已经尝试过此解决方案,但它不起作用。标题仍未添加。
    • 你的后端应该接受'Content-Type'
    • 后端使用了哪些技术
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-04
    • 2011-10-14
    • 2019-06-22
    • 1970-01-01
    • 1970-01-01
    • 2021-07-03
    • 1970-01-01
    相关资源
    最近更新 更多