2019年7月14日 星期日

[研究] 用VS2019 建 Node.js 的 Express 框架程式

[研究] 用VS2019 建 Node.js 的 Express 框架程式

2019-07-13


[研究] 用 VS2019 的 Node.js 建立 Web 應用程式 (Web App)
https://shaurong.blogspot.com/2019/07/vs2019-nodejs-web-web-app.html

Express - Node.js Web 應用程式架構
https://expressjs.com/zh-tw/
Express 是最小又靈活的 Node.js Web 應用程式架構,

Click 圖片可看 100% 原尺寸圖。






index.js

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

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

module.exports = router;


users.js
'use strict';
var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/', function (req, res) {
    res.send('respond with a resource');
});

module.exports = router;


error.pug
'use strict';
var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/', function (req, res) {
    res.send('respond with a resource');
});

module.exports = router;


index.pug
'use strict';
var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/', function (req, res) {
    res.send('respond with a resource');
});

module.exports = router;


layout.pug
doctype html
html
  head
    title= title
    link(rel='stylesheet', href='/stylesheets/main.css')
  body
    block content

app.js
'use strict';
var debug = require('debug');
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 routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

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

// uncomment after placing your favicon in /public
//app.use(favicon(__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')));

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

// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

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

app.set('port', process.env.PORT || 3000);

var server = app.listen(app.get('port'), function () {
    debug('Express server listening on port ' + server.address().port);
});


package.js
{
  "name": "express-app1",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node app"
  },
  "description": "ExpressApp1",
  "author": {
    "name": ""
  },
  "dependencies": {
    "body-parser": "^1.15.0",
    "cookie-parser": "^1.4.0",
    "debug": "^2.2.0",
    "express": "^4.14.0",
    "morgan": "^1.7.0",
    "pug": "^2.0.0-beta6",
    "serve-favicon": "^2.3.0"
  },
  "engines": {
    "node": "~6.10.x"
  }
}


Web.Config
<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your Node.js application, please visit
  http://go.microsoft.com/fwlink/?LinkId=290972
  -->
<configuration>
  <appSettings>
    <!--
    <add key="StorageAccountName" value="" />
    <add key="StorageAccountKey" value="" />
    <add key="ServiceBusNamespace" value="" />
    <add key="ServiceBusIssuerName" value="" />
    <add key="ServiceBusIssuerSecretKey" value="" />
    -->
  </appSettings>
  <system.webServer>
    <!-- mimeMap enables IIS to serve particular file types as specified by fileExtension. -->
    <staticContent>
      <mimeMap fileExtension=".svg" mimeType="image/svg+xml" />
    </staticContent>

    <modules runAllManagedModulesForAllRequests="false" />

    <!-- Web.Debug.config adds attributes to this to enable remote debugging when publishing in Debug configuration. -->
    <iisnode watchedFiles="web.config;*.js;routes\*.js;views\*.pug"/>

    <!-- Remote debugging (Azure Website with git deploy): Comment out iisnode above, and uncomment iisnode below. -->
    <!--<iisnode watchedFiles="web.config;*.js;routes\*.js;views\*.pug"
      loggingEnabled="true"
      devErrorsEnabled="true"
      nodeProcessCommandLine="node.exe &#45;&#45;debug"/>-->

    <!-- indicates that the server.js file is a Node.js application
    to be handled by the iisnode module -->
    <handlers>
      <add name="iisnode" path="app.js" verb="*" modules="iisnode" />

      <!-- Remote debugging (Azure Website with git deploy): Uncomment NtvsDebugProxy handler below.
      Additionally copy Microsoft.NodejsTools.WebRole to 'bin' from the Remote Debug Proxy folder.-->
      <!--<add name="NtvsDebugProxy" path="ntvs-debug-proxy/b65db3d4-7b86-44e4-8dc5-09eaa80ddf18" verb="*" resourceType="Unspecified"
        type="Microsoft.NodejsTools.Debugger.WebSocketProxy, Microsoft.NodejsTools.WebRole"/>-->
    </handlers>

    <security>
      <requestFiltering>
        <hiddenSegments>
          <remove segment="bin" />
        </hiddenSegments>
      </requestFiltering>
    </security>

    <rewrite>
      <rules>
        <clear />
        <!-- Remote debugging (Azure Website with git deploy): Uncomment the NtvsDebugProxy rule below. -->
        <!--<rule name="NtvsDebugProxy" enabled="true" stopProcessing="true">
          <match url="^ntvs-debug-proxy/.*"/>
        </rule>-->

        <!-- Don't interfere with requests for node-inspector debugging -->
        <rule name="NodeInspector" patternSyntax="ECMAScript" stopProcessing="true">
          <match url="^server.js\/debug[\/]?" />
        </rule>

        <rule name="app" enabled="true" patternSyntax="ECMAScript" stopProcessing="true">
          <match url="iisnode.+" negate="true" />
          <conditions logicalGrouping="MatchAll" trackAllCaptures="false" />
          <action type="Rewrite" url="app.js" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>

  <!-- Remote debugging (Azure Website with git deploy): uncomment system.web below -->
  <!--<system.web>
    <httpRuntime targetFramework="4.5"/>
    <customErrors mode="Off"/>
  </system.web>-->
</configuration>

Web.debug.config
<?xml version="1.0" encoding="utf-8"?>
<!-- This file will modify Web.config to enable remote debugging when publishing your project in the Debug configuration.
     For more information on using web.config transformation visit http://go.microsoft.com/fwlink/?LinkId=125889 -->
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">

  <system.web xdt:Transform="Insert">
    <httpRuntime targetFramework="4.5" />
    <customErrors mode="Off"/>
  </system.web>

  <system.webServer>
    <!-- mimeMap enables IIS to serve particular file types as specified by fileExtension. -->
    <staticContent>
      <mimeMap fileExtension=".svg" mimeType="image/svg+xml" />
    </staticContent>
 
    <iisnode loggingEnabled="true"
             devErrorsEnabled="true"
             nodeProcessCommandLine="node.exe --debug"
             xdt:Transform="SetAttributes" />

    <handlers>
      <!-- The GUID in the following path is meant to protect the debugging endpoint against inadvertent access, and should be treated as a password. -->
      <add name="NtvsDebugProxy" path="ntvs-debug-proxy/b65db3d4-7b86-44e4-8dc5-09eaa80ddf18" verb="*" resourceType="Unspecified"
           type="Microsoft.NodejsTools.Debugger.WebSocketProxy, Microsoft.NodejsTools.WebRole"
           xdt:Transform="Insert" />
    </handlers>

    <rewrite>
      <rules>
        <rule name="NtvsDebugProxy" enabled="true" stopProcessing="true" xdt:Transform="InsertAfter(/configuration/system.webServer/rewrite/rules/clear)">
          <match url="^ntvs-debug-proxy/.*"/>
        </rule>
      </rules>
    </rewrite>

  </system.webServer>

</configuration>


(完)

相關

[研究] 用VS2019 建立的 Node.js Console 程式
https://shaurong.blogspot.com/2019/07/vs2019-nodejs-console.html

[研究] 用 VS2019 的 Node.js 建立 Web 應用程式 (Web App)
https://shaurong.blogspot.com/2019/07/vs2019-nodejs-web-web-app.html

[研究] 用VS2019 建 Node.js 的 Express 框架程式
https://shaurong.blogspot.com/2019/07/vs2019-nodejs-express.html

沒有留言:

張貼留言