angular 介面請求不到資料的問題
阿新 • • 發佈:2018-11-04
最近在用ng5升級ext的老專案,發現post請求一直請求不到資料,最終發現原因是資料格式的問題。
伺服器介面接收的是form表單格式,而前端post請求傳送的是json資料格式。比如下面這個請求:
this.http.post(`${this.uri}/data/list.json`, req, headers);
export const headers = {headers: new HttpHeaders()};
HttpHeaders在例項化的時候預設生成的是json資料格式,如果要生成form表單格式的話,需要下面這樣寫:
export const headers = {headers: new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'})};
僅僅是更改了請求頭是不夠的,傳送form表單格式的資料需要將資料進行序列化,也就是拼接字串(如果使用jquery的ajax方法,它會在內部幫我們處理),手動拼接的話可以用下面的方式:
export function getFormData(obj) { let str = ''; let value; Object.keys(obj).map(key => { value = obj[key]; if (value instanceof Date) { str += key + '=' + format(value, 'YYYY-MM-DD HH:mm:ss') + '&'; } else if (value instanceof Object || value instanceof Array) { str += key + '=' + JSON.stringify(value) + '&'; } else if (value !== null || value !== undefined || value !== '') { str += key + '=' + value + '&'; } }); return str.length ? str.substr(0, str.length - 1) : str; }
最終的post請求如下:
this.http.post(`${this.uri}/data/list.json`, getFormData(req), headers);