通过Express格式错误从Node API对客户端(Angular2)的身体响应

时间:2017-03-06 20:07:22

标签: javascript json node.js angular express

当我的Angular2组件发出请求获取我的假模型数据对象时,它会像这样返回:

_body: "[↵ {↵ "id": 0,↵ "title": "2017 Oscars",↵ "graphic": "https://wikitags.com/images/OscarsBanner.png",↵

enter image description here

我期待的是像这样的数组:

[ 
  { 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

enter image description here

主页组件

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());
});

在终端中,我看到我的home.ts模型数组:

enter image description here

为什么我的res.body看起来很高兴?

1 个答案:

答案 0 :(得分:2)

看起来它可能正在尝试将json对象转换两次。虽然不完全确定

而不是res.json(homeData())

尝试:

res.send(homedata())

如果这不起作用,那么我的猜测就是转向角度并改变

.map(JSON.parse(res.json().data))