nodejs demo

1. app.js
var http = require('http');
var path = require('path');
var filter = require('./app_filter'); //url parsing
var express = require('./node_modules /express');
var session = require('express-session'); //Save user information in the background
var bodyParser = require('./node_modules/body-parser'); //Get the incoming information in the background
var cookieParser = require('./node_modules/cookie-parser'); //The browser saves the information
var app = express();


//The HTML template is changed to EJS, and the template suffix is ​​html
app.set('views', path.join (__dirname, 'views'));
app.engine('html', require('ejs').renderFile); //Set the page engine to html
app.set('view engine', 'html');      




app. use(bodyParser.json()); //If not, there will be no body object in req
app.use(bodyParser.urlencoded({extended: false}));


app.use(cookieParser("xx"));
app.use(express.static(path.join(__dirname, 'public'))); / /Static resource


var store = new session.MemoryStore(); //Set session
app.use(session({
    store: store,
    name: 'gcsoft.sid',
    secret: "webmeeting",
    resave: false,
    cookie: {maxAge : 60000 * 60 * 5},
    saveUninitialized: true
}));


app.use(filter.init); //url filtering


var routes = require('./web_routes'); //url parsing. Routing
app.use('/', routes);
module.exports = app; //module export


2. www.js startup file
var app = require('..
var http = require('http');


var server = http.createServer(app); //Create a server
app.set('port', 8080);
server.listen(8080) //Listen on port 8080


3. Filter app_filter
exports.init = function(req, res, next) {
    var ignore_url =['/sign','/checkUser']; //Array of ignored interfaces
    for (var i = 0; i < ignore_url.length; i++) {
        if (req.url.indexOf(ignore_url[i]) != -1) {
            return next(); //If ignored, enter the web_router route
        }
    }
    if (!req.session.user) { //Not logged in
        if (req.xhr) {
            //If it is an ajax request, return JSON
            return res.send({
                result_code: -1,
                message: "Not logged in"
            });
        } else {
            //If it is not an ajax request, return to the login page
            return res.redirect('http://' + req.headers.host + '/sign');
        }
        next( );
    }
    return next(); //Logged in, normal execution
}
4. Module introduction./
represents the current directory.

../ represents the upper level directory.

5.
Save and destroy the background session
req.session.user = data.userInfo;
req.session.destroy();
return to the page request: res.render('Index') will load Index.html
to return the status information of the operation : res.status(200).json({});
return data: res.send(data); directory structure

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325484258&siteId=291194637