Angular 8:URL编码形式为POST

问题描述 投票:1回答:2

我想将表单数据发布到接受并返回text / html / xml的服务器。我实际上是在尝试模仿普通的URL编码形式的POST。我的Angular 8 POST函数成功过帐(200 OK),但是服务器无法理解数据,因为它是JSON而不是URL编码。

响应和请求标头的状态为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\":\"[email protected]\",\"centreTelephoneNumberText\":123456789,\"centreNumberText\":\"ab123\",\"centreNameText\":\"ab123\",\"invoiceText\":\"123456789\",\"currencyText\":\"GBP\",\"amountText\":\"100\",\"cardtypeText\":\"Credit card\",\"commentsText\":\"Comments.\",\"declarationText\":true}":""}}

我想要的是:

[email protected]?centreTelephoneNumberText=123456789?centreNumberText=ab123?centreNameText=ab123?invoiceText=123456789?currencyText=GBP?amountText=100?cardtypeText=Credit card?commentsText=Comments.?declarationText=true
javascript angular forms post urlencode
2个回答
2
投票

我不确定这里的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对象。


0
投票

因此,此解决方案为我解决了各种问题:

  1. 使用Angular 8的表单和HttpClient发布x-www-form-urlencoded数据
  2. 更正不需要的编码字符
    • [我的特定问题是,唯一的验证字符串包含要转换为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()是突破,并且正如弗拉德(Vlad)建议的那样,绝对确定要处理的类型。我应该使用Types以避免混淆。我可能应该使用Angular Interceptors处理字符操作。

© www.soinside.com 2019 - 2024. All rights reserved.