EmberJS Express API | TypeError:app.route不是module.exports的函数

时间:2017-10-16 19:04:13

标签: node.js express ember.js mongoose promise

我已经被我的ember项目的服务器api难倒了一个星期了。我无法使用模块化的api工作,这让我疯狂。

控制台相关:
mongod,节点服务器,heroku本地(或者ember s)

首先,我试图解决的错误:(转到http://localhost:4500/notes时显示)

TypeError: app.route is not a function
    at module.exports (C:\Users\Accurate\Projects\emberjs\accurate2\AccurateEmber2\api\routes\noteRoute.js:21:9)
    at Layer.handle [as handle_request] (C:\Users\Accurate\Projects\emberjs\accurate2\AccurateEmber2\api\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (C:\Users\Accurate\Projects\emberjs\accurate2\AccurateEmber2\api\node_modules\express\lib\router\index.js:317:13)
    at C:\Users\Accurate\Projects\emberjs\accurate2\AccurateEmber2\api\node_modules\express\lib\router\index.js:284:7
    at Function.process_params (C:\Users\Accurate\Projects\emberjs\accurate2\AccurateEmber2\api\node_modules\express\lib\router\index.js:335:12)
    at next (C:\Users\Accurate\Projects\emberjs\accurate2\AccurateEmber2\api\node_modules\express\lib\router\index.js:275:10)
    at jsonParser (C:\Users\Accurate\Projects\emberjs\accurate2\AccurateEmber2\api\node_modules\body-parser\lib\types\json.js:109:7)
    at Layer.handle [as handle_request] (C:\Users\Accurate\Projects\emberjs\accurate2\AccurateEmber2\api\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (C:\Users\Accurate\Projects\emberjs\accurate2\AccurateEmber2\api\node_modules\express\lib\router\index.js:317:13)
    at C:\Users\Accurate\Projects\emberjs\accurate2\AccurateEmber2\api\node_modules\express\lib\router\index.js:284:7
    at Function.process_params (C:\Users\Accurate\Projects\emberjs\accurate2\AccurateEmber2\api\node_modules\express\lib\router\index.js:335:12)
    at next (C:\Users\Accurate\Projects\emberjs\accurate2\AccurateEmber2\api\node_modules\express\lib\router\index.js:275:10)
    at urlencodedParser (C:\Users\Accurate\Projects\emberjs\accurate2\AccurateEmber2\api\node_modules\body-parser\lib\types\urlencoded.js:91:7)
    at Layer.handle [as handle_request] (C:\Users\Accurate\Projects\emberjs\accurate2\AccurateEmber2\api\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (C:\Users\Accurate\Projects\emberjs\accurate2\AccurateEmber2\api\node_modules\express\lib\router\index.js:317:13)
    at C:\Users\Accurate\Projects\emberjs\accurate2\AccurateEmber2\api\node_modules\express\lib\router\index.js:284:7

这是我的文件夹架构:
API
- 控制器
- - - - noteController.js
- 模型
- - - - noteModel.js
- -node_modules
- -routes
- - - - noteRoute.js
- -package-lock.json
- 包装.json
- -server.js
应用
- - 序列发生器
- - - - note.js
配置
DIST
node_modules
公开
服务器
等等...

<小时/> 我的server.js文件:

// Allow POST, GET, PUT, DELETE, OPTIONS
app.use(function (req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
    next();
});

//DB Vars
var uri = 'mongodb://localhost/Ember2';

// mongoose instance connection url connection
mongoose.Promise = global.Promise;

var options = {
    useMongoClient: true
};
mongoose.connect(uri, function (err) {
    if (err) {
        console.log('ERROR connecting to: ' + uri + '. ' + err);
    } else {
        console.log('Succeeded connected to: ' + uri);
    }
});

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());


var note = require('./routes/noteRoute'); //importing route
app.use('/notes', note);

//middleware catch
app.use(function (req, res) {
    res.status(404).send({ url: req.originalUrl + ' not found' })
});

app.listen(port);


console.log('RESTful API server started on: ' + port);

我的noteRoute.js :(评论的代码是我尝试过的替代方案,但仍然收到错误。基本上,我无法与我的数据库进行交互。)

'use strict';
/*let router = require('express').Router();
let note = require('../controllers/noteController');

router.post('api/notes', note.create_a_note);
router.get('api/notes', function (req, res){
    note.list_all_notes});

module.exports = router;*/

module.exports = function (app) {
    let note = require('../controllers/noteController');
    let router = require('express').Router();

    router.post('api/notes', note.create_a_note);
    router.get('api/notes', function (req, res) {
        note.list_all_notes
    });

    // note Routes
    /*app.route('/notes')
        .get(note.list_all_note)
        .post(note.create_a_note);

    app.route('/notes/:noteId')
        .get(note.read_a_note)
        .put(note.update_a_note)
        .delete(note.delete_a_note);*/
};

我的noteModel.js:

'use strict'

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

let NoteSchema = new Schema({
    title: { 
        type: String, 
        required: 'Kindly enter the name of the note' 
    },
    content: { 
        type: String 
    },
    author: { 
        type: String 
    }
});

module.exports = mongoose.model('Notes', NoteSchema);

我的noteController.js:

'use strict';

let mongoose = require('mongoose'),
    Note = mongoose.model('Notes');

exports.list_all_notes = function(req, res){
    Note.find({}, function(err, note){
        if (err)
            res.send(err);
        res.json(note);
    });
};

exports.create_a_note = function(req, res){
    let new_note = new Note(req.body);
    new_note.save(function (err, note){
        if (err)
            res.send(err);
        res.json(note);
    });
};

exports.read_a_note = function(req, res){
    Note.findById(req.params.noteId, function(err, note){
        if (err)
            res.send(err);
        res.json(note);
    });
};

exports.delete_a_note = function(req, res){
    Note.remove({
        _id: req.params.noteId
    }, function(err, task){
        if (err)
            res.send(err);
        res.json({ message: 'Note successfully deleted.' });
    });
};

我的note.js序列化器:

import DS from 'ember-data';

export default DS.RESTSerializer.extend({
    /*primaryKey: '_id',
    serializeId: function (id) {
        return id.toString();
    }*/
    normalizeResponse(store, primaryModelClass, payload, id, requestType){
        payload = {notes: payload};

        payload.notes.foreach((note) => {
            note.id = note._id;
            delete note._id;
        });

        return this._super(store, primaryModelClass, payload, id, requestType);
    }
});

我一直在使用Postman和浏览器的组合来检查API状态 拥有这个模块化的API是必须的,因为应用程序将变得更大。将所有的get,post,put,delete等都放在server.js中会很麻烦。

1 个答案:

答案 0 :(得分:1)

noteRoutes.js应该是这样的:

let router = require('express').Router();
let note = require('../controllers/noteController');

router.post('/api/notes', note.create_a_note);
router.get('/api/notes', note.list_all_notes);

module.exports = router;

如果您使用此(您已有的)将其包含在server.js中:

var note = require('./routes/noteRoute');
app.use('/notes', note);

这会为您的http://localhost:4500/notes/api/notesGET请求提供POST的网址。如果这不是您想要的URL,则需要相应地调整路径路径。例如如果您只是想要http://localhost:4500/notes,请将路径更改为router.get('/', note.list_all_notes);,并将post()呼叫更改为相同。

然后,您需要解决控制器的问题。你反复使用这种模式:

if (err)
    res.send(err);
res.json(note);

这不起作用,在错误的情况下,它会尝试同时调用res.sendres.json,这会失败,因为您只能发送一个响应。

可能还有其他问题,但是当您遇到相关错误时,您需要调试它们。上面的建议应足以让您超越当前的错误。