Table of Contents
环境搭建
创建视图
路由
Home Web Front-end HTML Tutorial Express 网站开发_html/css_WEB-ITnose

Express 网站开发_html/css_WEB-ITnose

Jun 21, 2016 am 08:48 AM

express开发一个简单的网站,网页模板引擎使用 jade,样式基于 bootstrap,数据库使用 MongoDB

环境搭建

$ npm install express jade mongooes
Copy after login

首先需要是 node环境,使用 npm安装 express jade和 mongoose, 然后使用 bower 安装 bootstrap。

安装 bower 通过 npm install bower -g, bower 是一个客户端技术的软件包管理器,它可用于搜索、安装和卸载如JavaScript、HTML、CSS之类的网络资源。

$ bower install bootstrap
Copy after login

搭建完成后目录结构

├── app.js  # 启动文件├── bower_components # bower 安装的库│   ├── bootstrap│   └── jquery├── node_modules # npm 安装的依赖库│   ├── express│   ├── jade│   ├── moment│   └── mongoose├── package.json └── views # 视图模板    ├── includes    │   ├── head.jade    │   └── header.jade    ├── layout.jade    └── pages        ├── admin.jade        ├── detail.jade        ├── index.jade
Copy after login

创建视图

layout.jade基础布局,所有的网页都是基于该布局

doctypehtml  head    meta(charset="utf-8")    title #{title}    include ./includes/head  body    include ./includes/header    block content
Copy after login

head.jade放一些 css js 引用

link(href="/bootstrap/dist/css/bootstrap.min.css", rel="stylesheet")script(src="/jquery/dist/jquery.min.js")script(src="/bootstrap/dist/js/bootstrap.min.js")
Copy after login

header.jade所有网页通用的 header

.container  .row    .page-header      h1 #{title}
Copy after login

index.jade,主界面,影片列表

extends ../layoutblock content  .container    .row      each item in movies        .col-md-2          .thumbnail            a(href="/movie/#{item._id}")              img(src="#{item.poster}", alt="#{item.title}")            .caption              h3 #{item.title}              p: a.btn.btn-primary(href="/movie/#{item._id}", role="button") 观看预告片
Copy after login

detial.jade影片详情页,展示某个影片的详细信息

extends ../layoutblock content  .container    .row      .col-md-7        <video width="100%" controls="" autoplay="false" name="media"><source src="#{movie.flash}"></video>      .col-md-5        dl.dl-horizontal         dt 电影名字         dd #{movie.title}         dt 导演         dd #{movie.director}         dt 主演         dd #{ movie.actor}         dt 国家         dd #{ movie.country}         dt 语言         dd #{movie.language}         dt 上映年份         dd #{ movie.publishTime}         dt 类型         dd #{movie.type}         dt 简介         dd #{movie.summary}
Copy after login

admin.jadeAdmin 界面,录入影片信息。

extends ../layoutblock content  .container    .row      form.form-horizontal(method="post",action="/admin/movie/new")        .form-group          label.col-sm-2.control-label(for="inputTitle") 电影名字          .col-sm-10            input#inputTitle.col-sm-10.form-control(type="text",name="movie[title]")        .form-group          label.col-sm-2.control-label(for="inputDirector") 导演          .col-sm-10            input#inputDirector.col-sm-10.form-control(type="text",name="movie[director]")        .form-group          label.col-sm-2.control-label(for="inputCountry") 国家          .col-sm-10            input#inputCountry.col-sm-10.form-control(type="text",name="movie[country]")        .form-group          label.col-sm-2.control-label(for="inputLanguage") 语言          .col-sm-10            input#inputLanguage.col-sm-10.form-control(type="text",name="movie[language]")        .form-group          label.col-sm-2.control-label(for="inputYear") 上映年份          .col-sm-10            input#inputYear.col-sm-10.form-control(type="text",name="movie[publishTime]")        .form-group          label.col-sm-2.control-label(for="inputSummary") 简介          .col-sm-10            input#inputSummary.col-sm-10.form-control(type="text",name="movie[summary]")
Copy after login

list.jade影片列表编辑界面,编辑已有的文章。

extends ../layoutblock content  .container    .row      table.table.table-hover.table-bordered        thead          tr            th 电影名字            th 导演            th 国家            th 上映年份            //- th 录入时间            th 查看            th 更新            th 删除        tbody          each item in movies            tr(class="item-id-#{item._id}")              td #{item.title}              td #{item.director}              td #{item.country}              td #{item.publishTime}              //- td #{moment(item.meta.createdAt).format('MM/DD/YYYY')}              td: a(target="_blank", herf="../movie/#{item._id}") 查看              td: a(target="_blank", herf="../admin/update/#{item._id}") 修改              td                button.btn.btn-danger.del(type="button", date-id="#{item._id}") 删除
Copy after login

路由

var express = require('express')var path = require('path')var port = process.env.PORT || 3000var app = express()app.set('views','./views/pages')app.set('view engine', 'jade')app.use(express.static(path.join(__dirname,'bower_components')))app.listen(port)console.log('server listening on poert:'+port)// indexapp.get('/',function (req,res) {    res.render('index',{        title: '首页',        movies: [            {                title: '变形金刚1',                _id: 1,                poster: 'https://img3.doubanio.com/view/movie_poster_cover/mpst/public/p2332503406.jpg'            },            {                title: '变形金刚2',                _id: 2,                poster: 'https://img3.doubanio.com/view/movie_poster_cover/mpst/public/p2332503406.jpg'            },            {                title: '变形金刚3',                _id: 3,                poster: 'https://img3.doubanio.com/view/movie_poster_cover/mpst/public/p2332503406.jpg'            },            {                title: '变形金刚4',                _id: 4,                poster: 'https://img3.doubanio.com/view/movie_poster_cover/mpst/public/p2332503406.jpg'            }        ]    })});// movie detailapp.get('/movie/:id',function (req,res) {    res.render('detail',{        title: '详情页',        movie:{            title:'美国队长3:内战',            director: '安东尼&middot;罗素 / 乔&middot;罗素',            editor : '克里斯托弗&middot;马库斯 / 斯蒂芬&middot;麦克菲利 / 杰克&middot;科比 / 乔&middot;西蒙',            actor : '克里斯&middot;埃文斯 / 小罗伯特&middot;唐尼 / 斯嘉丽&middot;约翰逊 / 塞巴斯蒂安&middot;斯坦 / 安东尼&middot;麦凯 / 更多...',            type : '动作 / 科幻 / 冒险',            link : 'marvel.com/captainamerica',            country : '美国',            language : '科萨语 / 英语 / 德语 / 俄语 / 罗马尼亚语',            publishTime: ' 2016-05-06(中国大陆/美国) / 2016-04-12(加州首映)',            duration : '148分钟(中国大陆) / 147分钟',            alise : '美国队长3:内战 / 美国队长3:英雄内战(港/台) / 美队3 / Captain America 3',            summary : '美国队长史蒂夫&middot;罗杰斯(克里斯&middot;埃文斯 Chris Evans 饰)带领着全新组建的复仇者联盟,继续维护世界和平。然而,一次执行任务时联盟成员不小心造成大量平民伤亡,从而激发政治压力,政府决定通过一套监管系统来管理和领导复仇者联盟。联盟内部因此分裂为两派:一方由史蒂夫&middot; 罗杰斯领导,他主张维护成员自由,在免受政府干扰的情况下保护世界;另一方则追随托尼&middot;斯塔克(小罗伯特&middot;唐尼 Robert Downey Jr. 饰),他令人意外地决定支持政府的监管和责任制体系。神秘莫测的巴基(塞巴斯蒂安&middot;斯坦 Sebastian Stan 饰)似乎成为内战的关键人物……',            flash:'https://img3.doubanio.com/rda/8ffecbe972ad5cf.mp4'        }    })})//admin pageapp.get('/admin/movie', function (req, res) {    res.render('admin', {        title: 'imooc 后台录入页',        movie: {            director: '',            country: '',            title: '',            publishTime: '',            poster: '',            language: '',            flash: '',            summary: ''        }    })})//admin pageapp.get('/admin/list', function (req, res) {    res.render('list', {        title: 'imooc 列表页',        movies: [{            director: '乔斯&middot;韦登',            country: '美国',            title: '复仇者联盟2',            publishTime: '2015',            _id:2,            poster: 'http://img31.mtime.cn/mg/2015/03/27/120537.13212993_270X405X4.jpg',            language: '英语',            flash: 'http://v.youku.com/v_show/id_XODc4NDY0MjA4.html',            summary: '影片讲述当钢铁侠试图启动处于休眠状态的维持和平计划时,事情出了差错。于是,在地球面临生死存亡的紧急关头时,强大的超级英雄们挺身而出承担起拯救世界的重任,他们将阻止可怕的人工智能机器人“奥创”制定恐怖计划。'        }]    })})
Copy after login

目前还是假数据,还没有使用 MongoDB。

运行 node app.js然后再浏览器打开 http://localhost:3000。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Difficulty in updating caching of official account web pages: How to avoid the old cache affecting the user experience after version update? Difficulty in updating caching of official account web pages: How to avoid the old cache affecting the user experience after version update? Mar 04, 2025 pm 12:32 PM

The official account web page update cache, this thing is simple and simple, and it is complicated enough to drink a pot of it. You worked hard to update the official account article, but the user still opened the old version. Who can bear the taste? In this article, let’s take a look at the twists and turns behind this and how to solve this problem gracefully. After reading it, you can easily deal with various caching problems, allowing your users to always experience the freshest content. Let’s talk about the basics first. To put it bluntly, in order to improve access speed, the browser or server stores some static resources (such as pictures, CSS, JS) or page content. Next time you access it, you can directly retrieve it from the cache without having to download it again, and it is naturally fast. But this thing is also a double-edged sword. The new version is online,

How do I use HTML5 form validation attributes to validate user input? How do I use HTML5 form validation attributes to validate user input? Mar 17, 2025 pm 12:27 PM

The article discusses using HTML5 form validation attributes like required, pattern, min, max, and length limits to validate user input directly in the browser.

What are the best practices for cross-browser compatibility in HTML5? What are the best practices for cross-browser compatibility in HTML5? Mar 17, 2025 pm 12:20 PM

Article discusses best practices for ensuring HTML5 cross-browser compatibility, focusing on feature detection, progressive enhancement, and testing methods.

How to efficiently add stroke effects to PNG images on web pages? How to efficiently add stroke effects to PNG images on web pages? Mar 04, 2025 pm 02:39 PM

This article demonstrates efficient PNG border addition to webpages using CSS. It argues that CSS offers superior performance compared to JavaScript or libraries, detailing how to adjust border width, style, and color for subtle or prominent effect

What is the purpose of the <datalist> element? What is the purpose of the <datalist> element? Mar 21, 2025 pm 12:33 PM

The article discusses the HTML &lt;datalist&gt; element, which enhances forms by providing autocomplete suggestions, improving user experience and reducing errors.Character count: 159

What is the purpose of the <meter> element? What is the purpose of the <meter> element? Mar 21, 2025 pm 12:35 PM

The article discusses the HTML &lt;meter&gt; element, used for displaying scalar or fractional values within a range, and its common applications in web development. It differentiates &lt;meter&gt; from &lt;progress&gt; and ex

How do I use the HTML5 <time> element to represent dates and times semantically? How do I use the HTML5 <time> element to represent dates and times semantically? Mar 12, 2025 pm 04:05 PM

This article explains the HTML5 &lt;time&gt; element for semantic date/time representation. It emphasizes the importance of the datetime attribute for machine readability (ISO 8601 format) alongside human-readable text, boosting accessibilit

What is the purpose of the <progress> element? What is the purpose of the <progress> element? Mar 21, 2025 pm 12:34 PM

The article discusses the HTML &lt;progress&gt; element, its purpose, styling, and differences from the &lt;meter&gt; element. The main focus is on using &lt;progress&gt; for task completion and &lt;meter&gt; for stati

See all articles