0 부터 Node.js 시리즈 튜 토리 얼 의 connect 와 express 프레임 워 크 를 바탕 으로 하 는 다 중 페이지 에서 수학 연산 예 시 를 학습 합 니 다.
1.connect 프레임 사용
.use 방법 은 connect 서버 에 미들웨어 를 연결 하 는 데 사 용 됩 니 다.요청 을 받 았 을 때 호출 되 는 미들웨어 모듈 을 설정 합 니 다.이 경우 우리 가 설정 할 미들웨어 는 favicon logger static router 가 있 습 니 다.
app.get/post/put 쓰기:app.requestName('path',function(req,res,next){});
app-connect.js
 var connect = require('connect');  //npm install connect
 connect.createServer()
   .use(connect.favicon())
   .use(conect.logger())
   .use('/filez', connect.static(__dirname + '/filez'))
   .use(connect.router(function(app){
     app.get('/', require('./home-node').get);
     //  URL             
     //                  ,                    
     app.get('/square', htutil.loadParams, require('./square-node').get);
     app.get('/factorial', htutil.loadParams, require('./factorial-node').get);
     app.get('/fibonacci', htutil.loadParams, require('./fibo2-node').get);
     app.get('/mult', htutil.loadParams, require('./mult-node').get);
   })).listen(3000);
console.log('listening to http://localhost:3000');
Express 프레임 워 크 는 connect(미들웨어 프레임 워 크)를 기반 으로 한 웹 응용 프레임 워 크 입 니 다.
Express 는 템 플 릿 시스템 을 제공 하 는 것 을 포함 하여 응용 프로그램 을 구축 하 는 데 전념 합 니 다.connect 는 웹 서 비 스 를 위 한 인 프 라 에 전념 합 니 다.
Express 와 EJS(모듈 처리 시스템)npm install express ejs 설치
app-express.js
var htutil = require('./htutil');
var math = require('./math');
var express = require('express');
//var app = express.createServer(express.logger()); //express 2.X
var app = express();  //express 3.X
//  ,  Express    CWD/views
app.set('views', __dirname + '/views');
app.engine('.html', require('ejs').__express);
app.set('view engine', 'ejs');
app.configure(function(){
  app.use(app.router);
  app.use(express.static(__dirname + '/filez'));
  //         ,     
  //            ,app.err(function(err, req, res, next){
  // res.send(error page); //or res.render('template');
  // });
  app.use(express.errorHandler({
    dumpExceptions: true, showStack: true
  }));
/*
      ,             -Internal Server Error       
app.use(express.errorHandler({
    dumpExceptions: true
  }));
*/
});
//           ,                     ,  .html    EJS    
//        
app.get('/', function(req, res){
  res.render('home.html', {title: "Math Wizard"});
});
app.get('/mult', htutil.loadParams, function(req, res){
  if (req.a && req.b) req.result = req.a * req.b;
  res.render('mult.html', {title: "Math Wizard", req: req});
});
app.get('/square', htutil.loadParams, function(req, res){
  if (req.a) req.result = req.a * req.a;
  res.render('square.html', {title: "Math Wizard", req: req});
});
app.get('/fibonacci', htutil.loadParams, function(req, res){
  if (req.a){
    math.fibonacciAsync(Math.floor(req.a), function(val){
      req.result = val;
      res.render('fibo.html', {title: "Math Wizard", req: req});
    });
  }else {
    res.render('fibo.html', {title: "Math Wizard", req: req});
  }
});
app.get('/factorial', htutil.loadParams, function(req, res){
  if (req.a) req.result = math.factorial(req.a);
  res.render('factorial.html', {title: "Math Wizard", req: req});
});
app.get('/404', function(req, res){
  res.send('NOT FOUND' + req.url);
});
//res.render              ,EJS  Express           
//      EJS   views      .html    
/*Express           
  res.render('index.haml', {..data..});   Haml
  res.render('index.jade', {..data..});   Jade
  res.render('index.ejs', {..data..});   EJS
  res.render('index.coffee', {..data..});   CoffeeKup
  res.render('index.jqtpl', {..data..});   jQueryTemplates
      app.set('view engine', 'haml');
     app.set('view engine', 'jade');             
layout.html
     ,               body,     layout   , app-express.js  
res.render('fibo.html'...) ,    fibo.html         ,     layout        
              
1、 Express          ,           layout        
app.set('view options', {layout: false(or true)});
2、  layout                layout  
res.render('myview.ejs', {layout: false(or true)});
  res.render('page', {layout: 'mylayout.jade'});
<% code %> Javascript  
<%= code %>      HTML       
<%- code %>     HTML  
*/
app.listen(3000);
console.log('listening to http://localhost:3000');
layout.html
<!DOCTYPE html>
<html>
<head>
  <title></title>
</head>
<body>
  <h1><%=title%></h1>
  <table>
    <tr>
      <td>
        <div class="navbar">
          <p><a href="/" rel="external nofollow" >home</a></p>
          <p><a href="/mult" rel="external nofollow" >Multiplication</a></p>
          <p><a href="/square" rel="external nofollow" >Square</a></p>
          <p><a href="/factorial" rel="external nofollow" >Factorial</a></p>
          <p><a href="/fibonacci" rel="external nofollow" >Fibonacci</a></p>
        </div>
      </td>
      <td></td>
    </tr>
  </table>
</body>
</html>
<% include layout.html %>
<p>Math Wizard</p>
<% include layout.html %>
<% if (req.a && req.b){ %>
  <p class="result">
    <%=req.a%> * <%=req.b%> = <%=req.result%>
  </p>
<% } %>
<p>Enter numbers to multiply</p>
<form name="mult" action="/mult" method="get">
  A: <input type="text" name="a" /><br/>
  B: <input type="text" name="b" />
  <input type="submit" name="Submit" />
</form>
본 논문 에서 말 한 것 이 여러분 의 nodejs 프로 그래 밍 에 도움 이 되 기 를 바 랍 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Grunt에서 즉석 템플릿 엔진이 필요했기 때문에 마침내 만들었습니다.jade 라든지 ejs 라고도 좋지만, 보다 심플하게 하고 싶다고 생각해. json을 떨어 뜨렸다. 플레이스홀더(:TAG)를 마련해, 이런 HTML 만들어 둔다. template.html 자리 표시자의 문자열을 키로...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.