通过Express格式错误从Node API向客户端(Angular2)提供的身体响应
当我的Angular2组件发出一个请求来获取我的假模型数据对象时,它就像这样返回:
_body: "[↵ {↵ "id": 0,↵ "title": "2017 Oscars",↵ "graphic": "https://wikitags.com/images/OscarsBanner.png",↵
我期待的是一个像这样的数组:
[ { id: 0, title: '2017 Oscars', graphic: '/images/OscarsBanner.png', categorycards: [ [Object], [Object], [Object], [Object] ] }, { id: 1, title: '2017 Super Bowl', graphic: '/images/SuperBowlBanner.png', categorycards: [ [Object], [Object], [Object], [Object] ] }, { id: 2, title: 'What people are talking about', graphic: null, categorycards: [ [Object], [Object], [Object], [Object] ] } ]
该模型
什么我的backend/models/home.ts
看起来像
export function homeData() { return [ { id: 0, title: '2017 Oscars', graphic: '/images/OscarsBanner.png', categorycards: [ { type: 'image', graphic: 'https://upload.wikimedia.org/wikipedia/commons/thumb/f/fc/Ryan_Gosling_2_Cannes_2011_%28cropped%29.jpg/1024px-Ryan_Gosling_2_Cannes_2011_%28cropped%29.jpg?width=440', title: '2017 Oscar Nominee for Best Actor', listings: ['Rayn Gosling', 'Denzel Washington', 'Andrew Garfield', 'Casey Affleck', 'Viggo Mortensen'] } //... ] } //... ]; }
客户端API
api.service.ts
@Injectable() export class ApiService { private getFeaturedUrl: string = '/wiki/api'; constructor(public http: Http) {} /** * Get featured categories data for homepage */ getFeatured(): Observable<{}> { return this.http.get(`${this.getFeaturedUrl}/home`) .do(res => console.log('getFeatured res', res)) .map(res => res.json().data) .catch(this.handleError); }
console.log
在这里:
主页组件
universalInit() { console.log('universalInit...') this.api.getFeatured() .subscribe(categories => { console.log('categories', categories); // this.testFeaturedCategories = categories });
Node / Express API端点
// API CRUD //////////////////////////////////////////////////////////////////// app.get('/wiki/api/home', (req, res) => { console.log('homeData()', homeData()); if (!homeData()) returnError(res, 'No home data found'); res.json(homeData()); });
在terminal,我看到我的home.ts
模型arrays:
任何想法为什么我的res.body看起来抬头?
它看起来像它可能试图转换的JSON对象两次。 不完全确定
而不是res.json(homeData())
尝试:
res.send(homedata())
如果这不起作用,那么我的猜测就是走上有利的一面而改变
.map(JSON.parse(res.json().data))