位置 0 处 JSON 中的意外标记 J
Posted
技术标签:
【中文标题】位置 0 处 JSON 中的意外标记 J【英文标题】:Unexpected token J in JSON at position 0 【发布时间】:2018-11-25 17:37:23 【问题描述】:我正在尝试从 api 获取数据,在 post man 中测试了我的 api 一切正常,我只想在 get/movies 端点显示所有返回的电影。 这是我到目前为止所做的:
服务组件:
import Injectable from '@angular/core';
import Headers, Http, Response from '@angular/http';
@Injectable(
providedIn: 'root'
)
export class MoviesService
private apiUrl = 'http://localhost:8000/movies';
constructor(private http: Http)
getMovies(): Promise<any>
return this.http.get(this.apiUrl)
.toPromise()
.then(this.handleData)
.catch(this.handleError);
private handleData(res: any)
const body = res.json();
console.log(body); // for development purposes only
return body || ;
private handleError(error: any): Promise<any>
console.error('An error occurred', error); // for development purposes only
return Promise.reject(error.message || error);
这里的组件是我所拥有的:
import Component, OnInit from '@angular/core';
import Http from '@angular/http';
import Location from '@angular/common';
import MoviesService from '../movies.service';
@Component(
selector: 'app-movies',
templateUrl: './movies.component.html',
styleUrls: ['./movies.component.scss']
)
export class MoviesComponent implements OnInit
public movies: any;
public constructor(private http: Http, private location: Location, private moviesService: MoviesService)
this.movies = [];
ngOnInit(): void
this.location.subscribe(() =>
this.moviesService.getMovies();
);
this.moviesService.getMovies();
当我运行我的应用程序时,我收到以下错误:
movies.service.ts:24 An error occurred SyntaxError: Unexpected token J in JSON at position 0
at JSON.parse (<anonymous>)
at Response.push../node_modules/@angular/http/fesm5/http.js.Body.json (http.js:705)
at push../src/app/movies.service.ts.MoviesService.handleData (movies.service.ts:19)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:388)
at Object.onInvoke (core.js:3671)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (zone.js:387)
at Zone.push../node_modules/zone.js/dist/zone.js.Zone.run (zone.js:138)
at zone.js:872
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:421)
at Object.onInvokeTask (core.js:3662)
push../src/app/movies.service.ts.MoviesService.handleError @ movies.service.ts:24
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:388
onInvoke @ core.js:3671
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke @ zone.js:387
push../node_modules/zone.js/dist/zone.js.Zone.run @ zone.js:138
(anonymous) @ zone.js:872
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask @ zone.js:421
onInvokeTask @ core.js:3662
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask @ zone.js:420
push../node_modules/zone.js/dist/zone.js.Zone.runTask @ zone.js:188
drainMicroTaskQueue @ zone.js:595
push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask @ zone.js:500
invokeTask @ zone.js:1540
globalZoneAwareCallback @ zone.js:1566
error (async)
customScheduleGlobal @ zone.js:1666
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.scheduleTask @ zone.js:407
push../node_modules/zone.js/dist/zone.js.Zone.scheduleTask @ zone.js:232
push../node_modules/zone.js/dist/zone.js.Zone.scheduleEventTask @ zone.js:258
(anonymous) @ zone.js:1831
desc.set @ zone.js:1244
WebSocketTransport @ sockjs.js:2974
SockJS._connect @ sockjs.js:828
SockJS._receiveInfo @ sockjs.js:802
g @ sockjs.js:66
EventEmitter.emit @ sockjs.js:86
(anonymous) @ sockjs.js:567
g @ sockjs.js:66
EventEmitter.emit @ sockjs.js:86
(anonymous) @ sockjs.js:374
g @ sockjs.js:66
EventEmitter.emit @ sockjs.js:86
xhr.onreadystatechange @ sockjs.js:1593
wrapFn @ zone.js:1188
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask @ zone.js:421
push../node_modules/zone.js/dist/zone.js.Zone.runTask @ zone.js:188
push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask @ zone.js:496
invokeTask @ zone.js:1540
globalZoneAwareCallback @ zone.js:1566
XMLHttpRequest.send (async)
scheduleTask @ zone.js:2969
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.scheduleTask @ zone.js:407
push../node_modules/zone.js/dist/zone.js.Zone.scheduleTask @ zone.js:232
push../node_modules/zone.js/dist/zone.js.Zone.scheduleMacroTask @ zone.js:255
scheduleMacroTaskWithCurrentZone @ zone.js:1114
(anonymous) @ zone.js:3001
proto.(anonymous function) @ zone.js:1394
AbstractXHRObject._start @ sockjs.js:1601
(anonymous) @ sockjs.js:1490
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask @ zone.js:421
push../node_modules/zone.js/dist/zone.js.Zone.runTask @ zone.js:188
push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask @ zone.js:496
ZoneTask.invoke @ zone.js:485
timer @ zone.js:2054
setTimeout (async)
scheduleTask @ zone.js:2075
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.scheduleTask @ zone.js:407
push../node_modules/zone.js/dist/zone.js.Zone.scheduleTask @ zone.js:232
push../node_modules/zone.js/dist/zone.js.Zone.scheduleMacroTask @ zone.js:255
scheduleMacroTaskWithCurrentZone @ zone.js:1114
(anonymous) @ zone.js:2090
proto.(anonymous function) @ zone.js:1394
AbstractXHRObject @ sockjs.js:1489
XHRLocalObject @ sockjs.js:2910
InfoAjax @ sockjs.js:356
InfoReceiver._getReceiver @ sockjs.js:536
InfoReceiver.doXhr @ sockjs.js:556
(anonymous) @ sockjs.js:525
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask @ zone.js:421
push../node_modules/zone.js/dist/zone.js.Zone.runTask @ zone.js:188
push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask @ zone.js:496
ZoneTask.invoke @ zone.js:485
timer @ zone.js:2054
setTimeout (async)
scheduleTask @ zone.js:2075
push../node_modules/zone.js/dist/zone.js.ZoneDelegate.scheduleTask @ zone.js:407
push../node_modules/zone.js/dist/zone.js.Zone.scheduleTask @ zone.js:232
push../node_modules/zone.js/dist/zone.js.Zone.scheduleMacroTask @ zone.js:255
scheduleMacroTaskWithCurrentZone @ zone.js:1114
(anonymous) @ zone.js:2090
proto.(anonymous function) @ zone.js:1394
InfoReceiver @ sockjs.js:524
SockJS @ sockjs.js:730
initSocket @ socket.js:9
(anonymous) @ client?719c:211
./node_modules/webpack-dev-server/client/index.js?http://0.0.0.0:0 @ vendor.js:84316
__webpack_require__ @ bootstrap:76
0 @ main.ts:12
__webpack_require__ @ bootstrap:76
checkDeferredModules @ bootstrap:43
webpackJsonpCallback @ bootstrap:30
(anonymous) @ main.js:1
core.js:1542 ERROR Error: Uncaught (in promise): Unexpected token J in JSON at position 0
at resolvePromise (zone.js:814)
at resolvePromise (zone.js:771)
at zone.js:873
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:421)
at Object.onInvokeTask (core.js:3662)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:420)
at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:188)
at drainMicroTaskQueue (zone.js:595)
at ZoneTask.push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask [as invoke] (zone.js:500)
回复:
SONP_CALLBACK(page: 1, total_results: 364974, total_pages: 18249, results: [,…])
page
:
1
results
:
[,…]
0
:
vote_count: 595, id: 351286, video: false, vote_average: 6.7, title: "Jurassic World: Fallen Kingdom",…
1
:
vote_count: 2250, id: 383498, video: false, vote_average: 7.7, title: "Deadpool 2",…
2
:
vote_count: 6772, id: 284053, video: false, vote_average: 7.4, title: "Thor: Ragnarok",…
3
:
vote_count: 4857, id: 299536, video: false, vote_average: 8.4, title: "Avengers: Infinity War",…
4
:
vote_count: 1628, id: 338970, video: false, vote_average: 6.2, title: "Tomb Raider",…
5
:
vote_count: 11073, id: 135397, video: false, vote_average: 6.5, title: "Jurassic World",…
6
:
vote_count: 24, id: 525102, video: false, vote_average: 3.7, title: "Girl Lost",…
7
:
vote_count: 9056, id: 297762, video: false, vote_average: 7.2, title: "Wonder Woman",…
8
:
vote_count: 6114, id: 284054, video: false, vote_average: 7.3, title: "Black Panther",…
9
:
vote_count: 917, id: 348350, video: false, vote_average: 6.8, title: "Solo: A Star Wars Story",…
10
:
vote_count: 157, id: 402900, video: false, vote_average: 6.8, title: "Ocean's 8",…
11
:
vote_count: 13447, id: 118340, video: false, vote_average: 7.9, title: "Guardians of the Galaxy",…
12
:
vote_count: 2070, id: 337167, video: false, vote_average: 6, title: "Fifty Shades Freed",…
13
:
vote_count: 39, id: 260513, video: false, vote_average: 6.9, title: "Incredibles 2",…
14
:
vote_count: 641, id: 449176, video: false, vote_average: 8.3, title: "Love, Simon",…
15
:
vote_count: 9272, id: 10195, video: false, vote_average: 6.7, title: "Thor", popularity: 68.281475,…
16
:
vote_count: 0, id: 482560, video: false, vote_average: 0, title: "Covet: The Island of Desire",…
17
:
vote_count: 7119, id: 76338, video: false, vote_average: 6.7, title: "Thor: The Dark World",…
18
:
vote_count: 849, id: 268896, video: false, vote_average: 5.9, title: "Pacific Rim: Uprising",…
19
:
vote_count: 4733, id: 141052, video: false, vote_average: 6.3, title: "Justice League",…
total_pages
:
18249
total_results
:
364974
我在这里做错了什么?任何帮助将不胜感激
【问题讨论】:
那么 JSON 是什么样子的?handleData
和 handleError
有一个参数你没有传递。
@HotZellah 你能检查一下开发者工具中的浏览器网络选项卡,然后准确地粘贴从你的服务返回的内容吗?
不,这不是问题所在。该错误告诉您,您的代码期望的某些 JSON 内容无效。因此,如果没有实际看到该响应文本,就不可能说更多。
@Pointy 现在检查问题更新:我按照你的要求从浏览器发布了回复
【参考方案1】:
响应不是 JSON,而是 JSONP。这意味着它不是有效的 JSON,因此会出现解析错误。
您正在以返回JSONP 的方式调用该软件。如果这是默认返回类型,您需要将其更改为普通 JSON,以便您可以在编码时对其进行解析。如果这不可能,可能是因为您不控制后端并且无法添加 CORS 标头,您需要更改逻辑以主动使用 JSONP(这意味着您创建一个 global 函数名称JSONP_CALLBACK
- 通常通过参数配置以允许多个同时调用)或解决它。如果使用 JSONP 是因为 API 服务器在另一个域上并且没有设置 CORS,那么您无能为力。但是,如果设置了 CORS 标头或 API 端点位于同一个域中,您可以使用正则表达式简单地替换函数调用位,并留下一个您可以正常解析的常规 JSON 对象。
如果你不知道 wtf JSONP 是什么,你应该阅读this article。它基本上是 2010 年的 hack,现代浏览器和 CORS 不再需要它。
Angular 通过 $http.jsonp()
方法内置了对 JSONP 的支持。如果您需要有关如何使用 Angular 执行此操作的明确帮助,请参阅 this answer。
【讨论】:
您在后端使用 JSONP_CALLBACK 的权利,如果可行,我将立即更改,我会在一分钟内接受您的回答 记住函数必须是全局的——而不是局部的(隐藏在全局范围内)。顺便说一句,jQuery 支持内置的 JSONP。如果没有,您需要eval
回复。
以下是关于如何使用 Angular 执行此操作的答案:***.com/a/13400409/200987
这里我改变了private apiUrl = 'http://localhost:8000/movies'; constructor(private http: Http, private _jsonp: Jsonp) getMovies(): Promise<any> return this._jsonp.get(this.apiUrl) .toPromise() .then(this.handleData) .catch(this.handleError); private handleData(res: any) const body = res.json(); console.log(body); // for development purposes only return body || ;
仍然得到错误:错误:StaticInjectorError(AppModule)[MoviesService -> Jsonp]:
谢谢,现在可以工作了,只是在后端更改了回调,有或没有回调工作,再次感谢以上是关于位置 0 处 JSON 中的意外标记 J的主要内容,如果未能解决你的问题,请参考以下文章
SyntaxError:位置 0 处 JSON 中的意外标记 C
如何修复 SyntaxError:位置 0 处 JSON 中的意外标记 b
TypeScript 错误 TS5014:位置 0 处 JSON 中的意外标记 u
显示图像时 Object.parse 位置 0 处 JSON 中的意外标记