简体   繁体   English

找不到Express中的路线

[英]Route in Express not being found

I'm fairly new to building APIs with Node, Express and Mongo. 我对使用Node,Express和Mongo构建API还是很陌生。

I'm trying to modularize my Express Mongoose API, but for some reason my code is not seeing the exported route. 我正在尝试对Express Mongoose API进行模块化,但是由于某些原因,我的代码没有看到导出的路由。

When I use PostMan to test I get a 404 error. 当我使用PostMan进行测试时,出现404错误。

All my files are located in the same folder 我所有的文件都位于同一文件夹中

I have my main app.js file: 我有我的主要app.js文件:

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var cors = require('cors');

mongoose.connect('mongodb://localhost/guestbook');

var app = express();

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(cors());    

app.use('/api', require('./routes/api'));


    // changes it to use the optimized version for production
    app.use(express.static(path.join(__dirname, '/dist')));

    // production error handler
    // no stacktraces leaked to user
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: {}
        });
    });


module.exports = app;

I have my api.js file, which I reference in my app.js: 我有我的api.js文件,该文件在我的app.js中引用:

//DEPENDENCIES
var express = require('express');
var router = express.Router();


//include the routes file
var guestbook = require('./guestbook');

router.route('/guestbook');



//RETURN ROUTER AS MODULE
module.exports = router;

And finally my route, which is my guestbook.js file: 最后是我的路线,这是我的guestbook.js文件:

//DEPENDENCIES
var express = require('express');
var router = express.Router();


//GUESTBOOK END POINTS
var Guestbook = require('../models/guestbook')

router.route('/guestbook')

.post(function(req, res) {

    var guestbook = new Guestbook();

    guestbook.firstname = req.body.firstname;
    guestbook.lastname = req.body.lastname;
    guestbook.email = req.body.email;
    guestbook.postedon = req.body.postedon;
    guestbook.comment = req.body.comment;
    guestbook.rate = req.body.rate;

    guestbook.save(function(err) {
        if (err)
            res.send(err);

        res.json({ message: 'Post created!' })

    });

})

.get(function(req, res) {
    Guestbook.find(function(err, guestbook) {
        if (err)
            res.send(err);

        res.json(guestbook);
    });

});


router.route('/guestbook/:id')

.get(function(req, res) {

    Guestbook.findById(req.params.id, function(err, guestbook) {
        if (err)
            res.send(err);

        res.json(guestbook);

    });

})

.put(function(req, res) {

    Guestbook.findById(req.params.id, function(err, guestbook) {

        if (err)
            res.send(err);

        //USING OBJECT.KEYS TO UPDATE ONLY PARAMS PASSED
        Object.keys(req.body).forEach(function(prop) {
            if (typeof req.body[prop] !== 'undefined') {
                guestbook[prop] = req.body[prop];
            }
        });

        guestbook.save(function(err) {

            if (err)
                res.send(err);

            res.json(guestbook);

        });

    });

})

.delete(function(req, res) {

    Guestbook.remove({ _id: req.params.id }, function(err, guestbook) {
        if (err)
            res.send(err);
        res.json({ message: 'Successfully deleted!' });
    });

});


//RETURN ROUTER AS MODULE
module.exports = router;

If I were to rename my guestbook.js file to api.js and reference that directly from my app.js, everything works fine, but I'm trying to use an api.js file in the middle, so I can better organize my code. 如果我将guestbook.js文件重命名为api.js并直接从我的app.js引用,那么一切正常,但是我尝试在中间使用api.js文件,以便更好地组织我的码。

Any sage advice on how to fix this would be great!! 关于如何解决此问题的任何明智的建议都将非常棒!! Not sure what I'm missing that gives me the 404 error. 不知道我错过了什么,给我404错误。

You have a couple issues: 您有几个问题:

  1. You're using /guestbook too many times in your route definitions. 您在路由定义中使用/guestbook次数过多。
  2. You haven't actually hooked the guestbook.js into your routes. 您实际上并没有将guestbook.js挂接到路由中。

So, it appears you've created routes for: 因此,您似乎已经为以下路线创建了路线:

/api/guestbook/guestbook/
/api/guestbook/guestbook/:id

You need to remove one of the intervening .route('/guestbook') you have. 您需要删除插入的.route('/guestbook')

That's why when you remove the code in api.js that is doing the extra .route('/guestbook') , then things start to work. 这就是为什么当您删除api.js中正在执行额外的.route('/guestbook') ,事情开始起作用的原因。


You have to decide where you want to define the /guestbook part of the path. 您必须决定要在哪里定义路径的/guestbook部分。 If you want it defined in api.js , then you can just leave that as is and in guestbook.js , change this: 如果要在api.js定义它,则可以将其保留在guestbook.js ,并进行以下更改:

router.route('/guestbook')

to this: 对此:

router.route('/')

And, change this: 并且,更改此:

router.route('/guestbook/:id')

to this: 对此:

router.route('/:id')

And, then to hook guestbook.js into the routing chain, you can change this: 并且,然后将guestbook.js挂接到路由链中,您可以更改以下内容:

router.route('/guestbook');

to this: 对此:

// hook up guestbook router
router.use('/guestbook', guestbook);

在API.js中,您需要留言簿,但从不使用它,而只是导出未分配任何实际处理程序的裸路由器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM