今天在做项目的时候遇到了一个后台返回数据为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
- responseType -
{string}
- see XMLHttpRequest.responseType.
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(...);
Content-Type:application/json;charset=UTF-8