1.創建一個最簡單的項目
- 安裝nodejs
- 新建一個文件夾,進入目錄
mkdir express
- 接下來安裝 Express
npm install -g express-generator@4
- 創建一個工程
express helloworld 現在在express文件夾下就出現了helloworld項目
- 安裝依賴
cd helloworld npm install
備註:執行npm install命令會將package.json文件中 dependencies 依賴列表中, 即可自動安裝依賴列表中所列出的所有模塊。
- 開啓服務
執行npm start命令
- 這樣就可以在瀏覽器訪問
http://localhost:3000/
pic1.png
2.爲什麼瀏覽器中出現的內容是這樣的呢?
- 首先我們打開app.js,然後可以找到這句話
app.use('/', routes);
- 然後我們再看routes是什麼,就可以往上找,找到
var routes = require('./routes/index');
- 順着這個,我們打開routes文件夾下的index.js文件,看看裏面究竟寫的是什麼
var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index', { title: 'Express' }); }); module.exports = router;
-
原來框架是找到views文件夾下的index.jade文件渲染到前臺頁面
index.jade extends layout block content h1= title p Welcome to #{title}
- 這裏我們先不用管 模板引擎 的語法,試着修改修改index.js文件的內容,將title改爲Hello world.
var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index', { title: 'Hello world.' }); }); module.exports = router;
- 在命令行中,按ctrl+c關閉服務,重新執行npm start,看界面中的結果
pic2.png
是不是很簡單。
3.看到這裏,可能有個疑問,我們怎麼訪問靜態的html呢?
很簡單,下面一步步說來:
- 首先,我們看app.js中有沒有這句話
app.use(express.static(path.join(__dirname, 'public')));
- 有的話,則直接看下一步,沒有就在app.js中添加這句話,記得添加後重啓服務
- 接着,我們在項目的public文件夾下,新建一個html文件下(便於後期管理所有的靜態頁面),然後新建index.html,內容如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>demo</title> </head> <body> Hello world. </body> </html>
http://localhost:3000/html/index.html
4.我們現在做到了能訪問一個html文件,那我們如何模擬ajax請求,讀取json文件中的內容,提前綁定頁面呢?(不依賴後端接口寫好)
- 爲了方便項目管理,我們新建幾個文件夾和對應的文件
json文件夾及其對應的index.json文件 在javascripts文件夾下新建index.js
index.json { "code":"200", "msg":"success" }
index.js fetch("../json/index.json").then(function(res) { if (res.ok) { res.json().then(function(data) { console.log(data); }); } else { console.log("Looks like the response wasn't perfect, got status", res.status); } }, function(e) { console.log("Fetch failed!", e); });
- 在index.html中引入對應的文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>demo</title> </head> <body> Hello world. <script src="../javascripts/index.js"></script> </body> </html>
- 最後再打開訪問http://localhost:3000/html/index.html
打開控制檯,我們可以看到打印出了我們想要的內容
5.最後附上項目結構
快動手嘗試一下吧,以後前端開發再也不用等服務器端框架搭好,接口寫好了。