Express是一个基于Node.js的平台,快速、开放、极简的 web 开发框架,他提供一些列强大的特性,帮助你创建各种 web 和 移动设备应用。
cnpm install express --save
const express = require("express");
const app = express();
app.get('/', function(request, response){
response.send("hello nodejs");
})
app.get('/news', function(request, response){
response.send("获取新闻列表成功");
})
app.get('/news/:id', function(request, response){
let id = request.params["id"]
let query = request.query // {page: 10, offset: 0}
console.log(query);
response.send(`获取新闻${id}详情成功`);
})
app.listen(3000, 'localhost')
cnpm install ejs --save
// app.js
const express = require("express");
const app = express();
app.set("view engine", "ejs");
app.get('/', function(request, response){
let renderData = {
"index": "首页",
"content": "欢迎来到首页"
}
// 此处不需要写称:./views/index.ejs
response.render("index", {"data": renderData});
})
app.listen(3000, 'localhost')
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><%=data.index%>title>
head>
<body>
<p><%-data.content%>p>
body>
html>
<%- include('xxx.ejs')%>
views
// __dirname:当前目录
app.set('views', __dirname + '/views')
html
app.js
的头上定义ejs
,代码如下const ejs = require('ejs');
html
模板引擎代码如下app.engine('html', ejs.__express);
html
代码如下app.set('view engine', 'html');
.html
express.static
中间件:// public/css/base.css
app.use(express.static('public'))
ejs
模板引擎中进行引用<head>
<link rel="stylesheet" href="css/base.css">
head>
app.use('static', express.static('public'))
http://localhost:3000/static/images/logo.png