You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中重定向URL并携带Payload时如何设置请求头?

问题描述

我们已实现通过创建input元素向重定向URL发送Payload数据,但为该重定向URL设置请求头时,请求头无法生效。现寻求解决方案:在Angular中向重定向URL发送Payload数据时,如何设置Request Headers?

现有代码

app.component.html

<button (click)="redirectURL()">Redirect different URL</button>

app.component.ts

setHeader(url: any, newObj: any){
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "post", url);
    xmlHttp.setRequestHeader("iv-user", 'party_id');
    console.log('responseText : ' , xmlHttp.responseText);
    xmlHttp.onreadystatechange = function() {
      if(xmlHttp.readyState == 4) {
        alert(xmlHttp.responseText);
        console.log('xhr responseText : ' , xmlHttp.responseText);
        var data = xmlHttp.responseText;  
        var jsonResponse = JSON.parse(data);    
        return jsonResponse;
      }
    }
    xmlHttp.send(newObj);
    
    return xmlHttp.responseText;
}


redirectURL() {
  let form = document.createElement('form');
  console.log('form : ' , form);
  let actionUrl = "https://reqres.in/api/users";
  form.setAttribute('method',"post");
  form.setAttribute('action',actionUrl);
  form.setAttribute('style',"display:none");

  let a = document.createElement("input");
    a.type = "text";
    a.name = "party_id";
    a.value = "111111111";

    let b = document.createElement("input");
    b.type = "text";
    b.name = "party_id2";
    b.value = "2222222";

    let c = document.createElement("input");
    c.type = "text";
    c.name = "party_id3";
    c.value = "33333333";

    let d = document.createElement("input");
    d.type = "text";
    d.name = "party_id4";
    d.value = "44444444";

    let e = document.createElement("input");
    e.type = "text";
    e.name = "party_id5";
    e.value = "5555555";

    form.appendChild(a);
    form.appendChild(b);
    form.appendChild(c);
    form.appendChild(d);
    form.appendChild(e);

    document.getElementsByTagName('body')[0].appendChild(form);
    const myform = document.createElement('form');
    console.log('my form : ' , form);
    
    let newObj = {
      name: 'sk',
      job: 'developer'
    }
    this.setHeader("https://reqres.in/api/users", newObj);
  
    form.submit();
  
}
问题原因

当前代码存在两个核心问题:

  1. form.submit()是浏览器原生表单提交行为,浏览器不允许为这类请求自定义请求头,这是安全限制,表单提交只能发送默认头信息(比如Content-Type),无法添加iv-user这类自定义头。
  2. 同时调用setHeader(发起XHR请求)和form.submit()是两个完全独立的请求,表单提交的请求不会继承XHR里设置的任何头信息。
解决方案

方案一:使用Angular HttpClient发送带请求头的请求(需目标服务器支持CORS)

如果目标服务器允许跨域请求(配置了CORS相关响应头),可直接用Angular的HttpClient发送带自定义头的POST请求,无需通过表单提交:

  1. 在Angular模块(如AppModule)中导入HttpClientModule:
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    // ...其他导入项
    HttpClientModule
  ]
})
export class AppModule { }
  1. 在组件中注入HttpClient并修改redirectURL方法:
import { HttpClient, HttpHeaders } from '@angular/common/http';

// 组件构造函数注入HttpClient
constructor(private http: HttpClient) {}

redirectURL() {
  const actionUrl = "https://reqres.in/api/users";
  // 设置自定义请求头
  const headers = new HttpHeaders().set('iv-user', 'party_id');
  // 整合所有Payload数据
  const payload = {
    party_id: "111111111",
    party_id2: "2222222",
    party_id3: "33333333",
    party_id4: "44444444",
    party_id5: "5555555",
    name: 'sk',
    job: 'developer'
  };

  this.http.post(actionUrl, payload, { headers, observe: 'response' }).subscribe({
    next: (response) => {
      // 如需跳转,可根据响应结果处理,比如读取跳转地址
      // window.location.href = response.headers.get('Location') || actionUrl;
      console.log('请求成功', response);
    },
    error: (err) => {
      console.error('请求失败', err);
    }
  });
}

方案二:通过后端中转请求(无跨域限制)

如果目标服务器不支持CORS,或必须通过表单提交跳转,只能通过自身后端服务中转请求:

  1. 前端将表单数据提交到自己的后端接口。
  2. 后端接口接收数据后,带上自定义请求头iv-user,转发请求到目标URL。
  3. 后端处理目标URL的响应后,返回跳转指令给前端,前端再执行跳转或处理结果。

这种方式绕开了浏览器表单提交无法自定义头的限制,因为后端请求不受浏览器同源策略约束。

内容的提问来源于stack exchange,提问作者Salman Khan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 07:20:35