Angular4 http

在项目开发中使用了angular 的http,post 后台服务器一直接收不到,后来找大神问发现angular 使用的post 是原生的post 和jQuery 有所不同,这才明白。

jquery的send方法

jq对send方法内的data做了转化,成为以下方式。

1
?a=qweqewqe&b=awqder214ef&c=32424er;

这样的方式后台就可以收到了。

angular的send方法;

angular直接对send的data没有做任何处理,后台自然接收不到,并且angular的post头信息为:

1
"Content-Type":"application/json";

而 jQuery中的post 头为:

1
Content-Type:application/x-www-form-urlencoded; charset=UTF-8;

所以后台php 以及node都接受不到的;

解决办法

1
2
3
4
5
6
7
8
9
toFormJson(data: any) {
const str = [];
for (const item in data) {
if (item) {
str.push(encodeURIComponent(item) + ‘=’ + encodeURIComponent(data[item]));
}
}
return str.join(‘&’);
}

用toFormJson方法对data进行转化后再用xhr的send方法发送后台就可以接收到数据了