Express app - Change base url

对着背影说爱祢 提交于 2020-03-03 05:50:07

问题


I'm building a Q&A app following this tutorial and everything goes well, but I need to change the chance to change the base root where the app is being served via config files.

Now the app is served in localhost:8080 and I need to be served over localhost:8080/qae (for example).

I think the answer is near this piece of code:

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

(from /server/app.js)

But I can't figure it. Is it possible doing this in a simple way?

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

I tried all the proposed solutions, but I'm doing something wrong and got errors. This is my routes.js in case it helps:

/**
 * 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'));
    });
}

回答1:


You should change your rooting to this:

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

and in routes/index.js you can have all declarations of your routes.

In 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'));
      });
}

create file index.js in 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

That way all your api routes will look like /qae/api/*. If you need auth also after this prefix you need to do it same way. Best solution is to have i app.use('/',...) including routers from subfolders.




回答2:


You can do the following:

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

then you need to add route

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

Hope this helps :)




回答3:


If your ./routes module returned a router instead of taking an app object, then you could do this to make it available in / route:

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

or this to use /qae prefix:

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

but since you pass the app object to the function exported by ./routes then it is the ./routes module that actually registers the routes and since you didn't include its code it's hard to give you a specific example. I can only say that you will need to change the routes definitions in ./routes for a different prefix, and you'd need to return a router instead of taking app argument for the above examples to work.

Tthen you ./routes would have to look like this:

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

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

and only then you'll be able to use:

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

in the main code.




回答4:


Folder Structure

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;


来源:https://stackoverflow.com/questions/42902739/express-app-change-base-url

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!