Angular 10 如何为请求头追加X-Requested-With: XMLHttpRequest
解决方案
Angular 的 HttpHeaders 属于不可变对象,会严格保留请求头字段的插入顺序,你只需要在所有其他请求头配置完成后,最后插入 X-Requested-With 字段,就能保证它显示在请求头底部,两种常用实现方式如下:
方式1:初始化请求头时直接追加
// 先设置Content-Type,最后设置X-Requested-With,插入顺序会在请求头中保留 private _headers = new HttpHeaders() .set('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8') .set('X-Requested-With', 'XMLHttpRequest'); myRequest(data: string): Observable<string> { return this.http.post<string>(this.url, data, { headers: this._headers }); }
方式2:发起请求时动态追加
如果你的_headers是公共通用头,不想全局新增该字段,可以在单次请求时基于原有头生成新的头对象,最后追加目标字段:
private _headers = new HttpHeaders() .set('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); myRequest(data: string): Observable<string> { // 基于原有头追加,X-Requested-With为最后插入的字段,会显示在请求头底部 const finalHeaders = this._headers.set('X-Requested-With', 'XMLHttpRequest'); return this.http.post<string>(this.url, data, { headers: finalHeaders }); }
注意:
HttpHeaders的set/append方法不会修改原实例,只会返回新的头实例,必须接收返回的新对象配置才能生效。
内容的提问来源于stack exchange,提问作者bflow1
相关产品推荐
相关产品推荐

