search
HomeWeb Front-endHTML TutorialExpress 网站开发_html/css_WEB-ITnose

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

环境搭建

$ npm install express jade mongooes

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

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

$ bower install bootstrap

搭建完成后目录结构

├── 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

创建视图

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

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

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")

header.jade所有网页通用的 header

.container  .row    .page-header      h1 #{title}

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") 观看预告片

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}

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]")

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}") 删除

路由

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: '影片讲述当钢铁侠试图启动处于休眠状态的维持和平计划时,事情出了差错。于是,在地球面临生死存亡的紧急关头时,强大的超级英雄们挺身而出承担起拯救世界的重任,他们将阻止可怕的人工智能机器人“奥创”制定恐怖计划。'        }]    })})

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

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

Statement
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
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 <datalist> element, which enhances forms by providing autocomplete suggestions, improving user experience and reducing errors.Character count: 159

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 <progress> element, its purpose, styling, and differences from the <meter> element. The main focus is on using <progress> for task completion and <meter> for stati

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 <meter> element, used for displaying scalar or fractional values within a range, and its common applications in web development. It differentiates <meter> from <progress> and ex

What is the viewport meta tag? Why is it important for responsive design?What is the viewport meta tag? Why is it important for responsive design?Mar 20, 2025 pm 05:56 PM

The article discusses the viewport meta tag, essential for responsive web design on mobile devices. It explains how proper use ensures optimal content scaling and user interaction, while misuse can lead to design and accessibility issues.

What is the purpose of the <iframe> tag? What are the security considerations when using it?What is the purpose of the <iframe> tag? What are the security considerations when using it?Mar 20, 2025 pm 06:05 PM

The article discusses the <iframe> tag's purpose in embedding external content into webpages, its common uses, security risks, and alternatives like object tags and APIs.

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 <time> 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

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.

See all articles

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools