openshift express app提供静态文件

时间:2016-06-23 20:44:02

标签: node.js express static openshift

Noob在这里。我尝试使用express在Openshift上构建api服务器。我还希望能够从/ static文件夹中提供静态文件。问题是,我无法弄清楚如何在Openshift上进行设置。我已经尝试了所有我能想到的东西。

我有2个服务器文件,app设置调用路由的router.js文件。

app.js

    const express = require('express');
    const http = require('http');
    const bodyParser = require('body-parser');
    const morgan = require('morgan');
    const env = process.env;
    const app = express();
    const router = require('./router');
    const mongoose = require('mongoose');
    const cors = require('cors');


    // DB Setup
    // default to a 'localhost' configuration:
    var connection_string = '127.0.0.1:27017/api:api';
    // if OPENSHIFT env variables are present, use the available connection info:
    if(env.OPENSHIFT_MONGODB_DB_PASSWORD){
      connection_string = env.OPENSHIFT_MONGODB_DB_USERNAME + ":" +
      env.OPENSHIFT_MONGODB_DB_PASSWORD + "@" +
      env.OPENSHIFT_MONGODB_DB_HOST + ':' +
      env.OPENSHIFT_MONGODB_DB_PORT + '/' +
      env.OPENSHIFT_APP_NAME;
    }
    mongoose.connect('mongodb://' + connection_string);


    // App Setup
    app.use(morgan('combined')); //logging middleware
    app.use(cors()); // allow cross origin requests
    app.use(bodyParser.json({ type: '*/*'}));  //read requests as json

 ----->  do I need to put something here ????

    router(app);


    // Server Setup
    const port = env.NODE_PORT || 3090;
    const ip = env.NODE_IP || 'localhost';
    const server = http.createServer(app);
    server.listen(port, ip);
    console.log('Server listening on: ', port);

router.js

const Authentication = require('./controllers/authentication');
const passportService = require('./services/passport');
const passport = require('passport');
const requireAuth = passport.authenticate('jwt', { session: false});
const requireSignin = passport.authenticate('local', { session: false});

module.exports = function(app) {

 app.post('/signup', Authentication.signup);
 app.post('/signin', requireSignin, Authentication.signin);

 app.get('/health', function (req, res, next ) {
      res.writeHead(200);
    res.end();
 });

 ---->  and/or something here?
}

除了提供静态文件外,一切正常。不确定我是否需要将app.js文件中的内容作为中间件,路由器文件或两者。还不确定我是否需要使用Openshift环境变量?有人可以朝着正确的方向推动我吗?

1 个答案:

答案 0 :(得分:0)

在快递中,您可以使用express.static()

将以下内容添加到app.js来提供静态文件
var path = require('path');

// put this before all of your routes
app.use(express.static(path.join(__dirname, 'static')));