赞
踩
声明:本文记载为笔者根据官方文档及网上的博客创建Express项目以及对其进行项目配置的简单笔记,非精心创作,旨在记录,不保证其方法的优越性。
npx express-generator
express --view=pug myapp(myapp是项目名)
此应用将在当前目录下的 myapp 目录中创建,并且设置为使用 Pug 模板引擎
运行结果:
express --view=pug myapp create : myapp create : myapp/package.json create : myapp/app.js create : myapp/public create : myapp/public/javascripts create : myapp/public/images create : myapp/routes create : myapp/routes/index.js create : myapp/routes/users.js create : myapp/public/stylesheets create : myapp/public/stylesheets/style.css create : myapp/views create : myapp/views/index.pug create : myapp/views/layout.pug create : myapp/views/error.pug create : myapp/bin create : myapp/bin/www
安装依赖
进入myapp文件夹,使用npm install
或 yarn
,安装依赖
cd myapp
npm install(或yarn)
npm start
出现如下结果:
PS E:\Project\CloudFilmVueVersion-Practice\cloudFilm-vue\cloud-film-express> npm start
> cloud-film-express@0.0.0 start E:\Project\CloudFilmVueVersion-Practice\cloudFilm-vue\cloud-film-express
> node ./bin/www
以上结果表示运行成功,但是并不会自动打开浏览器,需要自行启动,
启动方法:在./bin/www中,找到启动端口,默认是3000,然后再浏览器访问:localhost:3000,即可。
express项目并不像react等前端框架,能够实时更新,即热加载,需要安装相关插件,实现类似效果。
使用nodemon实现热加载。
nodemon可以检测文件状态,并自动执行程序关闭和启动的操作,当项目文件发生改变时,nodemon会自动停止项目运行,然后重新启动,无需你自己操作,在使用上相当于是热加载了,但实际上是伪热加载。
npm install -g nodemon //全局安装
npm install --save-dev nodemon //安装为开发依赖
安装成功后,启动项目不再使用 npm start (等同于 node ./bin/www package.json中 start 处),而是
nodemon ./bin/www
运行结果:
PS E:\Project\CloudFilmVueVersion-Practice\cloudFilm-vue\cloud-film-express> nodemon ./bin/www
[nodemon] 2.0.4
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node ./bin/www`
由上可看到,实际上是nodemon工具帮你执行了 node ./bin/www
修改代码看看:
express默认是以CommonJS语法编写的,不支持ES6语法,若要是其支持,则需要安装和配置 babel
babel-core
npm install --save babel-core
babel-preset-env
或 babel-preset-es2015
npm install --save babel-preset-env
或
npm install --save babel-preset-es2015
babel-cli
pm install babel-cli -g
.babelrc
//.babelrc
{
"presets": ["env"],
"plugins": []
}
babel-node
来解析 js程序,并用 nodemon来实现热加载修改 package.json 文件中的scripts
"scripts": {
"start": "nodemon --exec babel-node ./bin/www" //./bin/www是你的启动文件
}
app.all('*', (req, res, next) => {
const { origin, Origin, referer, Referer } = req.headers;
const allowOrigin = origin || Origin || referer || Referer || '*';
res.header("Access-Control-Allow-Origin", allowOrigin);
res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res.header("Access-Control-Allow-Credentials", true);
res.header("X-Powered-By", 'Express');
if (req.method == 'OPTIONS') {
res.sendStatus(200);
} else {
next();
}
});
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。