如何使用Express

时间:2017-07-20 17:48:41

标签: node.js express model-view-controller

我有两个文件:一个index.html和一个server.js(下面的代码)。就目前而言,它们完美地运作。但是,据我所知,我需要在MVC中组织一些事情。我从头开始创建了一个项目,使用Express on Nodejs并根据我的需要进行了调整,但是我崩溃了这一部分。

问题:如何将这些代码与server.js文件分开?

//Loading modules
var http = require('http');
var fs = require('fs');
var path = require('path');
var b = require('bonescript');

// Create a variable called led, which refers to P9_14
var led = "P9_14";
// Initialize the led as an OUTPUT
b.pinMode(led, b.OUTPUT);

// Initialize the server on port 8888
var server = http.createServer(function (req, res) {
    // requesting files
    var file = '.'+((req.url=='/')?'/index.html':req.url);
    var fileExtension = path.extname(file);
    var contentType = 'text/html';
    if(fileExtension == '.css'){
        contentType = 'text/css';
    }
    fs.exists(file, function(exists){
        if(exists){
            fs.readFile(file, function(error, content){
                if(!error){
                    // Page found, write content
                    res.writeHead(200,{'content-type':contentType});
                    res.end(content);
                }
            })
        }
        else{
            // Page not found
            res.writeHead(404);
            res.end('Page not found');
        }
    })
}).listen(8888);

// Loading socket io module
var io = require('socket.io').listen(server);

// When communication is established
io.on('connection', function (socket) {
    socket.on('changeState', handleChangeState);
});

// Change led state when a button is pressed
function handleChangeState(data) {
    var newData = JSON.parse(data);
    console.log("LED = " + newData.state);
    b.digitalWrite(led, newData.state);
}

// Displaying a console message for user feedback
server.listen(console.log("Server Running ..."));

的index.html

<!DOCTYPE html>
<html>
<head>
    <title>Home Automation Web Server with BeagleBone</title>
    <link rel="stylesheet" href="stylesheet.css" type="text/css" />
    <script src = "/socket.io/socket.io.js" ></script>
    <script>
    // Your JavaScript code goes here
        // Establishing connection with server
        var socket = io.connect();
        // Changes the led state
        function changeState(state){
            if (state==1){
                // Emit message changing the state to 1
                socket.emit('changeState', '{"state":1}');
                // Change led status on web page to ON
                document.getElementById("outputStatus").innerHTML = "Status: ON";
            }
            else if (state==0){
                // Emit message changing the state to 0
                socket.emit('changeState', '{"state":0}');
                // Change led status on web page to OFF
                document.getElementById("outputStatus").innerHTML = "Status: OFF";
            }
        }
    </script>
</head>
<body>
<div id="wrapper">
    <div id="logo"><h1>Home Automation Web Server</h1></div>
    <div id="container" align="center">
        <h2>LED</h2>
        <p id="outputStatus">Status</p>
        <div id="buttons">
            <ul>
                <li><a onclick="changeState(1);">ON</a></li>
                <li><a onclick="changeState(0);">OFF</a></li>
            </ul>
        </div>
    </div>
    <div id="footer"><p>Powered by BeagleBone</p></div>
</div>
</body>
</html>

我做了什么:======================================= =============

文件app.js :包含这些行,创建路线:

var led = require('./routes/led');
app.use('/led', led);

文件/routes/led.js :包含视图渲染

var express     = require('express');
var router      = express.Router();
router.get('/', function(req, res, next) {
    res.render('led', { title: 'Liga led' });
});
module.exports = router;

接口文件led.pug :仅包含测试信息

doctype html
html
  head
    title= title
    link(rel='stylesheet', href='/stylesheets/style.css')
  body
    block content
block content
    h1= title
    p Welcome to #{title}    
    p Data = #{data}

1 个答案:

答案 0 :(得分:0)

我已经解决了:

<强> / bin中/万维网

&#34; var server = http.createServer(app);&#34;我补充说:     var io = require(&#39; socket.io&#39;)。listen(server);

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

router.get('/', function(req, res, next) {
    res.render('led', { title: 'Controle Cancela' });
});
module.exports = router;

<强> /router/led.js

<script>
    var socket = io.connect();
    function changeState(state) {
        if (state==1){
            socket.emit('changeState', '{"state":1}');
            document.getElementById("outputStatus").innerHTML = "Status: ON";
        }
        else if (state==0){
            socket.emit('changeState', '{"state":0}');
            document.getElementById("outputStatus").innerHTML = "Status: OFF";
        }
    }
</script>

<强> /javascripts/status.js

doctype html
html
  head
    title= title
    link(rel='stylesheet', href='/stylesheets/style.css')
    script(src='/socket.io/socket.io.js') 
    include ../public/javascripts/status.js
  body
    block content

block content
    h1= title
    p Welcome to #{title}

    p Data = #{data}

    div
        h2 LED
        p(id="outputStatus") Status
        div(id="buttons")
            ul
                li
                    a(onclick="changeState(1);") ON
                li
                    a(onclick="changeState(0);") OFF

<强> /views/led.pug

var led = require('./routes/led');

<强> /app.js

&#34; var index = require(&#39; ./ routes / index&#39;);&#34;我补充说:

app.use('/led', led);

&#34; app.use(&#39; /&#39;,index);&#34;我补充说:

var object1 = {"abc":{"name":"myabcname"}};
var object2 = {"def":{"name":"defname"}};

var mergedObject = Object.assign({}, object1, object2);

console.log(mergedObject);