我现在对Angular2非常好,但我从未使用过Express或REST。我想我现在已经正确设置了服务器,但是我无法正确地获取我的服务来转换数据。
我对服务器有效的原因是因为我可以导航到我的快速路线http://localhost:3000/api/foods
,我可以在那里观察我的休息api:
我已按照Angular2 HTTP Client 文档使用http.get 获取数据但我收到错误:
意外的令牌<在位置0的JSON中
我认为这是因为上面的图片中可以看到<html>
,但文档说res.json();
应该管理它。
问题是我是Express / REST菜鸟,我不知道如何正确转换数据。我不确定这是Express问题,MongoDB问题还是Angular / Angular CLI配置问题,我不知道如何找出它是什么。
以下是相关代码:
food.service.ts
import { Injectable } from '@angular/core';
import { Food } from '../../interfaces/diet/food'
import { Observable } from "rxjs/Rx";
import { Http, Response } from '@angular/http';
@Injectable()
export class FoodsService {
constructor(private http: Http) { }
getMongoFoods(): Observable<Food[]>{
console.log('called getMongoFoods');
return this.http.get('api/foods')
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
console.log(body);
return body.data || { };
}
private handleError (error: Response | any) {
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
}
server.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var path = require('path');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
Food = require('./routes/foods');
mongoose.connect('mongodb://localhost/cutcal');
var db = mongoose.connection;
app.get('/', function(req, res){
res.send('Please use /api/foods');
});
app.get('/api/foods', function(req, res){
Food.getFoods(function(err, foods){
if (err) { throw err; }
res.json(foods);
});
});
app.listen(3000);
console.log('running on port 3000');
foods.js
var mongoose = require('mongoose');
var foodSchema = mongoose.Schema({
name: {
type: String,
require: true
}
});
var Food = module.exports = mongoose.model('Food', foodSchema);
module.exports.getFoods = function(callback, limit){
Food.find(callback).limit(limit);
};