如何在Express中设置外部路由

时间:2015-12-27 16:11:27

标签: javascript node.js express hyperlink routing

我一直在制作Express应用程序。我设法让index路线正常工作。我正在尝试添加名为cart的新路由,这会将用户带到购物车页面。但是,我无法设置cart路由进行连接。我收到404错误。这很奇怪,因为我设置的路线与index相同。

我刚刚注意到,当我打开链接时,它会路由到/shoppingcart.html,而不只是/shoppingcart。这没有任何意义,因为我没有HTML文件,并将链接设置为/shoppingcart(如下所示)。 如果我将它们作为/ routename输入,我能够访问所有路由,但是当我尝试从索引页面访问它们时,它们都变成了/routename.html。有谁知道如何改变这个?

List of files

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 routes = require('./routes/index');
var cart = require('./routes/cart');
//var users = require('./routes/users');

var app = express();

// view engine setup
// Only needed if we use jade, we could use jade to route to html, but no point
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// 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: false }));
app.use(cookieParser());
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/shoppingcart', cart);
//app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// 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;

car.js

var express = require('express');
var router = express.Router();
// GET cart page. 
router.get('/shoppingcart', function(req, res, next) {
  res.render('cart', { title: 'Shopping cart' });
});

module.exports = router;

layout.jade

doctype html
html
  head
    meta(charset="utf-8")
    meta(http-equiv="X-UA-Compatible", content="IE=edge")
    meta(name="viewport", content="width=device-width, initial-scale=1")
    meta(name="description", content="")
    meta(name="author", content="")
    title Store Web page 
    // CSS
    link(href="/stylesheets/bootstrap.min.css", rel="stylesheet")
    link(href="/stylesheets/style_red.css", rel="stylesheet")
    link(href="/stylesheets/font-awesome/css/font-awesome.min.css", rel="stylesheet", type="text/css")
    // JS
    script(src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js")
    script(src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-route.js")
    script(src="/javascripts/angular-ui-router.min.js")
    script(src="script.js")
  body
    header
      // Navigation
      nav.navbar.navbar-inverse.navbar-fixed-top(role="navigation")
        .container
          // Brand and toggle get grouped for better mobile display
          .navbar-header
            button.navbar-toggle(type="button", data-toggle="collapse", data-target="#bs-example-navbar-collapse-1")
              span.sr-only Toggle navigation
              span.icon-bar
              span.icon-bar
              span.icon-bar
            a.navbar-brand(href="index.html") Andrew Kralovec E-learning Studio
          // Collect the nav links, forms, and other content for toggling
          #bs-example-navbar-collapse-1.collapse.navbar-collapse
            ul.nav.navbar-nav.navbar-right
              li
                a(href="about.html") About
              li
                a(href="fourm.html") Forum
              li
                // CART ROUTE 
                a(href="/shoppingcart") Cart
              li.dropdown
                a.dropdown-toggle(href="#", data-toggle="dropdown")
                  | Support
                  b.caret
                ul.dropdown-menu
                  li
                    a(href="tutorials.html") Tutorials
                  li
                    a(href="documents.html") Documents
                  li
                    a(href="common.html") Common questions
                  li
                    a(href="ticket.html") Kralovec support
              li
                a(href="contact.html") Contact
    // i like the layout options to jade 
    block content
  // Bottom page, wont work in the index jade 
  script(src='/javascripts/jquery.js')
  // Bootstrap Core JavaScript
  script(src='/javascripts/bootstrap.min.js')
  // Menu Toggle Script
  script.
    $("#menu-toggle").click(function(e) {
    e.preventDefault();
    $("#wrapper").toggleClass("toggled");
    });
  footer
    | @John 2015

cart.jade

extends layout
// shopping cart page 
block content
 .container
    table#cart.table.table-hover.table-condensed
    thead
        tr
        th(style='width:50%') Product
        th(style='width:10%') Price
        th(style='width:8%') Quantity
        th.text-center(style='width:22%') Subtotal
        th(style='width:10%')
    tbody
        tr
        td(data-th='Product')
            .row
            .col-sm-2.hidden-xs
                img.img-responsive(src='http://placehold.it/100x100', alt='...')
            .col-sm-10
                h4.nomargin Product 1
                p
                | Quis aute iure reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Lorem ipsum dolor sit amet.
        td(data-th='Price') $1.99
        td(data-th='Quantity')
            input.form-control.text-center(type='number', value='1')
        td.text-center(data-th='Subtotal') 1.99
        td.actions(data-th='')
            button.btn.btn-info.btn-sm
            i.fa.fa-refresh
            button.btn.btn-danger.btn-sm
            i.fa.fa-trash-o
        tr
        td(data-th='Product')
            .row
            .col-sm-2.hidden-xs
                img.img-responsive(src='http://placehold.it/100x100', alt='...')
            .col-sm-10
                h4.nomargin Product 2
                p
                | Quis aute iure reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Lorem ipsum dolor sit amet.
        td(data-th='Price') $3.99
        td(data-th='Quantity')
            input.form-control.text-center(type='number', value='1')
        td.text-center(data-th='Subtotal') 3.99
        td.actions(data-th='')
            button.btn.btn-info.btn-sm
            i.fa.fa-refresh
            button.btn.btn-danger.btn-sm
            i.fa.fa-trash-o
    tfoot
        tr.visible-xs
        td.text-center
            strong Total 1.99
        tr
        td
            a.btn.btn-warning(href='#')
            i.fa.fa-angle-left
            |  Continue Shopping
        td.hidden-xs(colspan='2')
        td.hidden-xs.text-center
            strong Total $1.99
        td
            a.btn.btn-success.btn-block(href='#')
            | Checkout 
            i.fa.fa-angle-right

1 个答案:

答案 0 :(得分:0)

您是否正在访问/ shoppingcart / shoppingcart端点?这就是你所暴露的。如果您只想公开/ shoppingcart,那么您想要在/:

的cart.js中安装路线
// GET cart page. router.get('/', function(req, res, next) { 
res.render('cart', { title: 'Shopping cart' }); }); 

您在发布的代码中再次重复该路线:

router.get('/shoppingcart'...