Angular8:URL编码形式POST

Angular 8: URL encoded form POST

我想 post 将数据发送到接受 returns text/html/xml 的服务器。我正在有效地尝试模拟正常的 URL 编码形式 POST。我的 Angular 8 POST 函数成功 posts (200 OK),但服务器无法理解数据,因为它是 JSON 而不是 URL 编码.

响应和请求 headers 状态 Content-Type: text/html; Charset=utf-8Accept: text/html, application/xhtml+xml, */* 并且我已将 responseType: "text" 添加到 httpClient 选项。为什么服务器仍在发送 JSON 而不是 URL 编码数据?

// obj2 = output from ngForm
// baseUrl2 = server that sends and receives text/html/xml

public postForm(obj2) {
    return this.httpClient
    .post(this.baseUrl2, obj2, {
        headers: new HttpHeaders({
            "Content-Type": "application/x-www-form-urlencoded",
            Accept: "text/html, application/xhtml+xml, */*"
        }),
        responseType: "text"
    })
    .map(data => data);
}

已发送表单数据:

{"Form data":{"{\"personsNameText\":\"name9\",\"centreEmailAddressText\":\"name9@name.com\",\"centreTelephoneNumberText\":123456789,\"centreNumberText\":\"ab123\",\"centreNameText\":\"ab123\",\"invoiceText\":\"123456789\",\"currencyText\":\"GBP\",\"amountText\":\"100\",\"cardtypeText\":\"Credit card\",\"commentsText\":\"Comments.\",\"declarationText\":true}":""}}

我想要的:

personsNameText=name9?centreEmailAddressText=name9@name.com?centreTelephoneNumberText=123456789?centreNumberText=ab123?centreNameText=ab123?invoiceText=123456789?currencyText=GBP?amountText=100?cardtypeText=Credit card?commentsText=Comments.?declarationText=true

我不确定这里 obj2 对象的类型,但我假设它类似于

interface UserFormData {
  ['Form data']: { [name: string]: value };
}

您需要在发布前将其转换为 FormData。沿线的东西:

const formEncodedObj2 = new FormData();
const obj2Keys = obj2['Form data'];
Object.keys(obj2Keys).forEach(key => formEncodedObj2.append(key, obj2Keys[key]));

然后发送formEncodedObj2对象。

所以,这个解决方案为我解决了各种问题:

  1. 使用 Angular 8 的表单和 HttpClient
  2. 发布 x-www-form-urlencoded 数据
  3. 更正不需要的编码字符
    • 我的具体问题是一个唯一的验证字符串包含被转换为 HTML 实体的符号,即 &&
// userdata.service.ts

public postForm(obj) {
  return this.httpClient
    .post(this.baseUrl2, obj, {
      headers: new HttpHeaders({
        "Content-Type": "application/x-www-form-urlencoded",
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
        "Referer": "http://referer.com" // Replace with your own.
      }),
      responseType: "text"
    })
    .map(data => data)
    .pipe(
      retry(1),
      catchError(this.handleError)
    );
}

// app.component.ts

PostForm(userdata) {
    // Stringify and convert HTML entity ampersands back to normal ampersands.
    const corrected = JSON.stringify(userdata).replace(/(&)/gm, '&');
    // Convert back to JSON object.
    const corrected2 = JSON.parse(corrected);
    // entries() iterates form key:value pairs, URLSearchParams() is for query strings
    const URLparams = new URLSearchParams(Object.entries(corrected2));
    // Convert to string to post.
    const final = URLparams.toString();
    // Post it
    this.userdataService.postForm(final).subscribe(reponse2 => {
        console.log(reponse2);
    });
}

URLSearchParams() was the breakthrough and, as Vlad suggested, being absolutely sure of the type one is dealing with. I should have used Types to avoid confusion. I probably should use Angular Interceptors 处理字符操作。