啊哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈 啊哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈 写了一中午的博客 最后莫名其妙死机
(第一次 第一次 第一次死机 啊 真的是 刚刚哭哭的不行 抹着泪重新写的时候发现提示 什么什么已保存草稿 灵光一现 找了找发现我的博客还在啊 呜呜呜呜呜·~)
差点气死了 哼哼~! \!!^!!/
--------------------------------------------------我是分割线-------------------------------------------------------------
首先,在命令行创建express项目文件
第一步、cd C:\Users\15891678176\Desktop
第二步、express FirstApp -e (桌面上出现FirstApp文件夹)
第三步、cd FirstApp
第四步、npm install (在FirstApp文件下出现了node_module文件夹和package-lock.json)
第四步、npm start (localhost:3000 进入Welcome to Express)
app.js下代码:
// res.send('hello world'); 页面输出展示hello world 字符串
// res.render('index'); 页面输出展示view目录下的index.html中的内容
在目录命令行下:npm install nodemon --save-dev (node 自动启动工具)
package.json下改动为红框 (原代码为 "start":"node ./bin/www"
这样就是搭建了一个简单的服务器 在localhost:5000下展示了hello world
----------------------------------------我是分割线--------------------------------------------------
下面是把view下index.ejs进行页面展示
app.js代码
const
express =
require(
'express');
var
app =
express();
//生成一个实例
var
path =
require(
'path');
//用于处理文件路径的小工具
app.
set(
'views',
path.
join(
__dirname,
'views'));
app.
set(
'view engine',
'ejs');
var
indexRouter =
require(
'./routes/index');
var
usersRouter =
require(
'./routes/users');
app.
get(
'/',
function(
req,
res){
let
articles = [
{
id :
1,
title :
'Title one',
author:
'haohao'
},
{
id :
2,
title :
'Title two',
author:
'kexin'
}
]
res.
render(
'index',{
title:
'Articles',
articles:articles
});
// {title:'Articles'} 是给变量title赋值了Articles title可以在html中引用展示出来
})
app.
get(
'/articles/new',
function(
req,
res){
// "/articles/new"的意思为在localhost:5000
res.
render(
'new',{
// 后面加上 /articles/new 可以访问new.ejs页面
title:
'Add Articles'
});
})
app.
listen(
5000,
function(){
console.
log(
"Server started on post 5000...");
//监听5000端口
})
view下index.ejs代码
<!-- index.ejs -->
<
h1
>嘤嘤嘤嘤嘤嘤嘤嘤嘤
</
h1
>
<
h1
>好饿好饿好饿真的好饿饿 \qaq/
</
h1
>
<
h1
>
<%= title %>
</
h1
>
<
hr/
>
<!-- for循环 -->
<%for(var i=0; i
< articles.length; i++){ var u = articles[i];%>
<!-- '<%' 和 '%>' 分别在行的起始和末尾呦~ 还夹了一个'{' -->
<!-- 定义u等于数组的第[i]项元素 -->
<
h2
>
<%=u.id%> ||
<%=u.title%> ||
<%=u.author%>
</
h2
>
<!-- 这个地方 '<% %>' 是在<h2></h2>里面呦~ -->
<%}%>
<!-- 看见没有 '<%'和'%>'中间就夹了一个 '}' 另外半个在上面,看到没有 猜到了什么???? -->
1.<%%>标签里可以写js代码-定义变量
- <% var data = 50;var hello = '<h3>hello world</h3>' %>
2.<%=%>和<%-%> 区别 前者不会编译,后者会编译
- <h2>data的值为 : <%=data%></h2>
- <%=hello%><br>
- <%-hello%>
运行结果:
到这里我们就能在localhost:5000下看到