如何向我的 Angular 发布请求添加标头?

问题描述:

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

For a school project I need to make a simple login page with Angular. When a login button is clicked I need to add an Authorization header with my post. I created a backend and when I post my Authorization value to that backend with postman it works so nothing wrong with the backend. When I try to post to the same backend with my frontend it doesn't work. What is the best way to add headers to your post? It seems that the opinions are divided. This is my code:

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 状态响应并且没有添加标头.

When I run that code I get a 400 status response and the headers are not added.

第二个参数传入HttpClient.post 代表请求的正文,但您在此处提供Headers.使用以下内容正确提供标题:

The second argument passed in to HttpClient.post represents the body of the request, but you're providing Headers here. Use the following to provide the headers correctly:

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

我已经在正文的示例中显示了 null,但您可能希望在某些情况下包含 emailpassword 属性形式.

I've shown null in the example for the body, but you probably want that to include the email and password properties in some form.

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

You're also mixing Http and HttpClient. If you're going to use HttpClient (which is now the recommended approach), drop RequestOptions and Headers in favour of HttpHeaders. This becomes:

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

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

The rest of the code stays the same. Your createAuthorizationHeader function needs to use and return an instance of HttpHeaders. This class is immutable, so append returns a new object each time it is called. Import HttpHeaders from @angular/common/http.