angular $http get post使用过程中遇到的错误

来源:互联网 发布:汽车模拟软件 编辑:程序博客网 时间:2024/05/06 22:58

get方式:

error:Uncaught SyntaxError: Unexpected token :

跨域只需在后台设置下头文件,前端不用设置。

错误原因:请求方式使用了jsonp
解决方式:将jsonp换为get,angular版本在1.5以上的,回调函数使用then

post方式:

1.error415 Unsupported Media Type2.error:SyntaxError: Unexpected token in JSON at position x

去百度搜索第一种错误有好多网友会提供这个答案:
contentType : ‘application/json’
但小编将application/x-www-form-urlencoded换为json控制台会报第二种错误。
最后小编发现不是我大前端的问题,后端的返回值格式不是json就会报错。只要让后端返回json格式就可以了。

最后奉上小编的代码:
get

$http.get(url)        .then(          function (res) {            console.log(res);          },          function (err) {            console.log(err);          }        );

post

$http.post(        url,        data,        {'Content-Type':'application/x-www-form-urlencoded'})        .then(          function (res) {            console.log(res);          },          function (err) {            console.log(err);          });

还有chorm有个关于跨域问题的插件Allow-Control-Allow-Origin: *
小编遇到过同一个接口在另一个程序中可用但是在这个程序中不能用,加载了这个插件就可以了。
亲测可通,如遇到各种奇葩错误,欢迎留言。

0 0
原创粉丝点击