[英]Angular 5 HttpClient: Send POST params as URL encoded string
[英]Angular 8: URL encoded form POST
我想將表單數據發布到接受並返回 text/html/xml 的服務器。 我正在有效地嘗試模擬普通的 URL 編碼形式的 POST。 My Angular 8 POST function successfully posts (200 OK), but the server can't understand the data because it is JSON and not URL encoded.
響應和請求頭 state Content-Type: text/html; Charset=utf-8
Content-Type: text/html; Charset=utf-8
和Accept: text/html, application/xhtml+xml, */*
我在 httpClient 選項中添加了responseType: "text"
。 為什么服務器仍在發送 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
object 的類型,但我假設它類似於
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
object。
所以,這個解決方案為我解決了各種問題:
&
到&
.// 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 建議的那樣,絕對確定要處理的類型。 我應該使用類型來避免混淆。 我可能應該使用Angular 攔截器來處理字符操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.