快递应用 - 更改基本网址

时间:2017-03-20 11:45:25

标签: node.js express

我正在this tutorial之后构建一个Q& A应用程序,一切顺利,但我需要更改通过配置文件更改应用程序所在位置的基础的机会。

现在应用程序在localhost:8080中提供,我需要通过localhost:8080 / qae(例如)提供。

我认为答案就在这段代码附近:

// Setup server
var app = express();
var server = http.createServer(app);
var socketio = require('socket.io')(server, {
  serveClient: config.env !== 'production',
  path: '/socket.io-client'
});
require('./config/socketio')(socketio);
require('./config/express')(app);
require('./routes')(app);


// Start server
function startServer() {
  app.angularFullstack = server.listen(config.port, config.ip, function() {
    console.log('Express server listening on %d, in %s mode '+config.ip, config.port, app.get('env'));
  });
}

setImmediate(startServer);

(来自/server/app.js)

但我无法理解。是否有可能以一种简单的方式做到这一点?

//////// EDIT ////////

我尝试了所有提议的解决方案,但我做错了什么并且出错了。这是我的routes.js以防万一:

/**
 * Main application routes
 */

'use strict';

import errors from './components/errors';
import path from 'path';

export default function(app) {
  // Insert routes below
  app.use('/api/cpd', require('./api/cpd'));
  app.use('/api/categories', require('./api/category'));
  app.use('/api/terms', require('./api/term'));
  app.use('/api/qae', require('./api/qae'));
  app.use('/api/stats', require('./api/stat'));
  app.use('/api/tags', require('./api/tag'));
  app.use('/api/questions', require('./api/question'));
  app.use('/api/things', require('./api/thing'));
  app.use('/api/users', require('./api/user'));

  app.use('/auth', require('./auth'));

  app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
  });


  // All undefined asset or api routes should return a 404
  app.route('/:url(api|auth|components|app|bower_components|assets)/*')
   .get(errors[404]);

  // All other routes should redirect to the index.html
  app.route('/*')
    .get((req, res) => {
      res.sendFile(path.resolve(app.get('appPath') + '/index.html'));
    });
}

4 个答案:

答案 0 :(得分:2)

您可以执行以下操作:

var app = express();
var routes = require('./routes/index');   
app.set('base', '/qae');

然后你需要添加路线

app.use('/qae', routes);

希望这会有所帮助:)

答案 1 :(得分:1)

您应该将生根改为:

app.use('/qae',require('./routes'))

并且在routes/index.js中,您可以获得路线的所有声明。

routes.js

export default function(app) {
    // Insert routes below
    app.use('/qae', require('./api'));


    app.use('/auth', require('./auth'));

    app.use(function(req, res, next) {
      res.header("Access-Control-Allow-Origin", "*");
      res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
      next();
    });


    // All undefined asset or api routes should return a 404
    app.route('/:url(api|auth|components|app|bower_components|assets)/*')
    .get(errors[404]);

    // All other routes should redirect to the index.html
    app.route('/*')
      .get((req, res) => {
        res.sendFile(path.resolve(app.get('appPath') + '/index.html'));
      });
}

index.js

中创建文件api
const express = require('express')
const router = express.Router()

router.use('/api/cpd', require('./cpd'));
router.use('/api/categories', require('./category'));
router.use('/api/terms', require('./term'));
router.use('/api/qae', require('./qae'));
router.use('/api/stats', require('./stat'));
router.use('/api/tags', require('./tag'));
router.use('/api/questions', require('./question'));
router.use('/api/things', require('./thing'));
router.use('/api/users', require('./user'));

module.exports = router

这样你所有的api路线都会看起来像/qae/api/*。如果您在此前缀后也需要auth,则需要以相同的方式执行此操作。 最佳解决方案是让i app.use('/',...)包含子文件夹中的路由器。

答案 2 :(得分:0)

如果您的./routes模块返回了路由器而不是app个对象,那么您可以执行此操作以使其在/路由中可用:

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

或者使用/qae前缀:

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

但是由于您将app对象传递给./routes导出的函数,因此实际注册路由的是./routes模块,因为您没有包含其代码很难给你一个具体的例子。我只能说您需要更改./routes中的路由定义以获取不同的前缀,并且您需要返回路由器而不是采用app参数来使上述示例工作

然后你./routes必须看起来像这样:

let express = require('express');
let router = express.Router();

router.get('/xxx', (req, res) => {
    // ...
});
router.get('/yyy', (req, res) => {
    // ...
});
module.exports = router;

只有这样你才能使用:

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

在主要代码中。

答案 3 :(得分:0)

文件夹结构

bin/
  www
server/
  routes/
    index.js
    book.js
  views/
    index.ejs
  app.js
  router.js
  error.js
public/
package.json

<强> 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 app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// 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(express.static(path.join(__dirname, 'public')));

require('./router')(app);
require('./errors')(app);


module.exports = app;

<强> route.js

var index = require('./routes/index');
var books = require('./routes/books');

var base = '/api';

module.exports = function (app) {
    app.use(base+'/', index);
    app.use(base+'/books', books);
};

<强> error.js

module.exports = function (app) {
    app.use(function (req, res, next) {
        var err = new Error('Not Found');
        err.status = 404;
        next(err);
    });

// 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
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: {}
        });
    });
};

<强> index.js

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

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

module.exports = router;