gpt4 book ai didi

javascript - 如何解决: Unexpected token < in JSON at position 0

转载 作者:行者123 更新时间:2023-12-03 04:13:53 25 4
gpt4 key购买 nike

您好:我正在接触 MEAN 堆栈。所以我使用 Angular 连接到 api.js 文件,该文件与我的 mongodb 数据库连接。但是,我收到以下错误:

ERROR SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at Response.Body.json (http.es5.js:800)
at MapSubscriber.project (post.service.ts:19)
at MapSubscriber._next (map.js:77)
at MapSubscriber.Subscriber.next (Subscriber.js:89)
at XMLHttpRequest.onLoad (http.es5.js:1229)
at ZoneDelegate.invokeTask (zone.js:424)
at Object.onInvokeTask (core.es5.js:4140)
at ZoneDelegate.invokeTask (zone.js:423)
at Zone.runTask (zone.js:191)

错误中引用的post.service.ts文件如下:

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class PostService {

result: any;

constructor(private _http: Http) { }

getPosts() {
return this._http.get("/api/posts")
.map(result => this.result = result.json());
}

getPost(id) {
return this._http.get("/api/details" + id)
.map(result => this.result = result.json());
}

}

以下是我的 api.js 文件。即使控制台也不会记录该帖子。

router.get('/details/:id', function(req, res) {
console.log('Requesting post');
post.findById(req.params.id)
.exec(function(err, post) {
if (err) {
console.log('Error getting the post');
} else {
res.json(post);
console.log(post);
}
});
});

我不确定我哪里出错了。我将不胜感激任何指导。

最佳答案

您的 api 缺少某些部分,假设您将请求发送到未找到帖子或服务器错误,然后您不向客户端发送回任何内容或错误 html。所以尝试向客户端发送消息,例如:

 if (err) {
console.log('Error getting the post');
res.status(500).json({error: err.message, errorCode: /*some number code*/ 1101});
} else {
/* logic for not found maybe */
// and logic for result
res.json(post);
console.log(post);
}

url 应该是:get("/api/details/"+ id)

关于javascript - 如何解决: Unexpected token < in JSON at position 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44223974/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com