AngularJS如何解码带有令牌和内部用户信息的jsonp响应

AngularJS How to decode a jsonp response with a token and user infomation inside?

本文关键字:用户 内部 信息 响应 jsonp 令牌 何解码 解码 AngularJS      更新时间:2024-03-01

在我的angularJS应用程序中,我在jsonp http请求后得到以下响应。

angular.callbacks._1({
  "token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ2IjowLCJpYXQiOjE0NjAxMDQ3MzIsImQiOnsidWl...",
    "user":{
    "uid":"lda...",
    "sn":"Hugo",
    "mail":"abc@bla.com",
    "mobile":""
    }})

当我对这个响应进行json解析时。

JSON.parse(response)

出现"SyntaxError:Unexpected token o"的错误。有人能帮我解码这个json字符串吗?

angular.js:13283 SyntaxError: Unexpected token o
    at Object.parse (native)
    at http://127.0.0.1:8080/bower_components/satellizer/satellizer.js:518:34
    at processQueue (http://127.0.0.1:8080/bower_components/angular/angular.js:15616:28)
    at http://127.0.0.1:8080/bower_components/angular/angular.js:15632:27
    at Scope.$eval (http://127.0.0.1:8080/bower_components/angular/angular.js:16884:28)
    at Scope.$digest (http://127.0.0.1:8080/bower_components/angular/angular.js:16700:31)
    at Scope.$apply (http://127.0.0.1:8080/bower_components/angular/angular.js:16992:24)
    at done (http://127.0.0.1:8080/bower_components/angular/angular.js:11313:47)
    at completeRequest (http://127.0.0.1:8080/bower_components/angular/angular.js:11511:7)
    at http://127.0.0.1:8080/bower_components/angular/angular.js:11421:9

JSONP返回的是JavaScript对象,而不是包含JSON的JavaScript字符串。(尽管名称不同,JSONP不是JSON。它是JavaScript。)

它由JavaScript解析器解析。

当您调用JSON.parse(response)时,您隐含地调用JSON.parse(response.toString()),这将为您提供JSON.parse("[object Object]")

只需直接使用response,不要试图将其视为JSON。

var token = response.data.token;
var user = response.data.user;

您可以在AngularJS 中尝试

                        var token = response.data['token']
                        var user = response.data['user']