最近在用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);