如何在角度2中添加标题到帖子请求?

时间:2017-05-31 22:22:31

标签: angular angular2-http

POST
  

我想在此请求中添加以下标题:
  "标题":
{
" content-type":" application / json",
      " access_token":" abcd"
    }

3 个答案:

答案 0 :(得分:8)

@Injectable()
export class UserService {
    constructor (private http:HttpClient) {}

    getUserByName(username: string) {
        let url="http://localhost:8088/rest/user/userName";
        let header=new Headers({'Content-Type': 'application/json', 'Authorization': 
            'Bearer '+localStorage.getItem("access_token")});
        return this.http.post(url, username, {headers: header});
    }
}

答案 1 :(得分:2)

试试这个

 let headers = new Headers({ "content-type": "application/json", });
    headers.append('access_token', "abcd");
    let options = new RequestOptions({ headers: headers });

 this.http
      .post(url, data, options)

答案 2 :(得分:0)

你可以

let headers = new HttpHeaders(); headers = headers.set(...); headers = headers.set(...); headers = headers.set(...);

let headers = new HttpHeaders().set(...)
                                     .set(...)
                                     .set(...);

参考:issue with post request http header angular 4

如果在角度2

let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('authentication', `${student.token}`);

let options = new RequestOptions({ headers: headers });
return this.http
    .put(url, JSON.stringify(student), options)