AngularJS - $http的config

今天在做项目的时候遇到了一个后台返回数据为String的API

最开始的时候直接使用$http.post调用:

$http.post(url).then(...);

然后前台console里面就会报这样的错。跳到error的回调函数里面,但是后台的操作都是成功了的

SyntaxError: Unexpected token s
    at Object.parse (native)
    at fromJson (http://localhost:23087/admin/vendor/angular/angular.js:1326:14)
    at defaultHttpResponseTransform (http://localhost:23087/admin/vendor/angular/angular.js:10515:16)
    at http://localhost:23087/admin/vendor/angular/angular.js:10606:12
    at forEach (http://localhost:23087/admin/vendor/angular/angular.js:321:20)
    at transformData (http://localhost:23087/admin/vendor/angular/angular.js:10605:3)
    at transformResponse (http://localhost:23087/admin/vendor/angular/angular.js:11403:21)
    at processQueue (http://localhost:23087/admin/vendor/angular/angular.js:16170:28)
    at http://localhost:23087/admin/vendor/angular/angular.js:16186:27
    at Scope.parent.$get.Scope.$eval (http://localhost:23087/admin/vendor/angular/angular.js:17444:28)(anonymous function) @ angular.js:13708ident.$get @ angular.js:10347processQueue @ angular.js:16178(anonymous function) @ angular.js:16186parent.$get.Scope.$eval @ angular.js:17444parent.$get.Scope.$digest @ angular.js:17257parent.$get.Scope.$apply @ angular.js:17552done @ angular.js:11697completeRequest @ angular.js:11903requestLoaded @ angular.js:11836
angular.js:13708 
Broken interceptor detected: Config object not supplied in rejection:
 https://github.com/chieffancypants/angular-loading-bar/pull/50

因为$http服务会直接把response解析成json,后台返回值为String时就会报上面的错误。


去angular.js的官方文档上面查了一圈,又学到了许多新的知识。可以通过设置config对象的属性来改变默认的http请求行为。

  • headers – {Object} – Map of strings or functions which return strings representing HTTP headers to send to the server. If the return value of a function is null, the header will not be sent. Functions accept a config object as an argument.
  • transformResponse –{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>} – transform function or an array of such functions. The transform function takes the http response body, headers and status and returns its transformed (typically deserialized) version. See Overriding the Default Transformations
一开始去设置
headers: {content-Type: "text/html" }
后来发现这只能改变request的header


设置

responseType: "text"
仍然没有达到想要的效果(不知道为什么)


设置

transformResponse: function(data) {  // 转换response
     return data;
}
这个奏效了。


为了保险,同时加上了responseType和transformResponse

$http.post(url, null, {
    responseType: "text",
    transformResponse: function(data) {  // 转换response
        return data;
    }
}).then(...);


但是response的Content-Type仍然是json,只是可以正确调到success的回调函数了。
Content-Type:application/json;charset=UTF-8


求小伙伴解答。



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值