node[15]-express

最简单的服务器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const express = require('express');

var app = express();


//返回html格式
app.get('/',(req,res)=>{
  res.send('<h1>Hello world</h1>');
});

//返回json格式
app.get('/fast',(req,res)=>{
  res.send({
      name:'json',
      likes:[
        'reading',
        'coding'
      ]
  });
});
//监听端口
app.listen(3000);

访问:
localhost:3000
localhost:3000/fast

访问静态文件

创建public/help.html

1
2
3
4
5
6
7
8
9
10
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <h1>Hello Jonson</h1>
  </body>
</html>

express.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
const express = require('express');

var app = express();

// 参数是一个middleware
app.use(express.static(__dirname +'/public'));
//返回html格式
app.get('/',(req,res)=>{
  res.send('<h1>Hello world</h1>');
});

//返回json格式
app.get('/fast',(req,res)=>{
  res.send({
      name:'json',
      likes:[
        'reading',
        'coding'
      ]
  });
});
//监听端口,  第二个回调是开启服务器后调用
app.listen(3000,()=>{
  console.log('hello jonson');
});

访问:
http://localhost:3000/help.html
会打开public/help.html的页面并显示出来。

动态注入 express template engines

1
npm install --save hbs

新建views/about.hbs:

1
2
3
4
5
6
7
8
9
10
11
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <h1>{{currentYear}}</h1>
    <footer>{{pageTitle}}</footer>
  </body>
</html>

express.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
const express = require('express');
const hbs = require('hbs');
var app = express();

app.set('view engine','hbs');




// 参数是一个middleware
app.use(express.static(__dirname +'/public'));
//返回html格式
app.get('/',(req,res)=>{
  res.send('<h1>Hello world</h1>');
});

//返回json格式
app.get('/fast',(req,res)=>{
  res.send({
      name:'json',
      likes:[
        'reading',
        'coding'
      ]
  });
});

//动态传递参数。
app.get('/about',(req,res)=>{
  res.render('about.hbs',{
    pageTitle:'About Page',
    currentYear:new Date().getFullYear()
  });
});
//监听端口,  第二个回调是开启服务器后调用
app.listen(3000,()=>{
  console.log('hello jonson');
});

访问:
localhost/about

 

 

郑建勋(jonson)区块链工程师 & Web工程师

灾难总是接踵而至,这正是世间的常理。你以为只要哭诉一下,就会有谁来救你吗?如果失败了,就只能说明我不过是如此程度的男人。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值