nodejs問世已經好幾年了,一直沒有用它開發過一個項目,即便是最簡單的項目,實屬遺憾。html
最多隻是create一個http服務器,一直好奇用node作api接口應該如何實現。前端
學習了下網上一些博客,原來就是使用 koa-router 註冊路由,添加一些 get/post 的請求。node
如下是主要流程:es6
首先,建個文件夾,而後進入文件夾目錄下, npm init ,再下載依賴項:ajax
npm i koa
npm i koa-router
npm i koa-bodyparser
複製代碼
1.新建一個 controllers 文件夾,文件夾內是接口具體實現的js文件npm
// controllers/users/UserController.js
class UserController {
// 用戶登陸
async login(ctx, next) {
// 獲取請求提交的數據
let name = ctx.request.body.name || '',
pwd = ctx.request.body.pwd || '';
console.log(name, pwd);
// do something
ctx.body = {
status: true,
token: '123'
}
}
// 用戶信息
async userInfo(ctx, next) {
// do something
// 假設這是請求回來的數據
let data = {
name: 'jk',
age: 25
}
ctx.body = {
status: true,
data
};
}
}
module.exports = new UserController();
複製代碼
2.再建一個 router 文件夾,文件夾有一個index.js, 聲明一些用到的接口。json
// router/index.js
// 加載依賴
const router = require('koa-router')();
const userctrl = require('../controllers/users/UserController');
router
// 用戶模塊
.post('/api/user/login', userctrl.login)
.get('/api/user/userinfo', userctrl.userInfo);
// .put('xxx')
// .delete('xxx')
module.exports = router;
複製代碼
3.而後就是 app.js 了api
// app.js
// 加載依賴
const koa = require('koa');
const router = require('koa-router')();
const bodyParser = require('koa-bodyparser');
const apiRouter = require('./router');
const app = new koa();
// 首頁
const index = router.get('/', ctx => {
ctx.response.body = 'hello world';
}).routes();
app.use(index);
app.use(bodyParser());
app.use(apiRouter.routes());
app.listen(3000);
複製代碼
好了,代碼都敲完了,運行下看看吧瀏覽器
node app.js
複製代碼
打開瀏覽器,鍵入bash
localhost:3000
複製代碼
會看到 hello, world。
再輸入
localhost:3000/api/user/userinfo
複製代碼
能看到以下數據
{"status":true,"data":{"name":"jk","age":25}}
複製代碼
這也算是一個get請求了。前端用 ajax 直接請求數據亦可。
測試post請求的話,須要一個表單頁。
咱們就新建一個 demos的文件夾,裏面放一些模板吧
// demos/login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>login</title>
</head>
<body>
<input type="text" id="name">
<input type="password" id="pwd">
<button id="submit_btn">提交</button>
<script>
const xhr = new XMLHttpRequest();
document.getElementById('submit_btn').addEventListener('click', login, false);
function login() {
let data = {
name: document.getElementById('name').value,
pwd: document.getElementById('pwd').value,
}
xhr.open('POST', '/api/user/login');
xhr.setRequestHeader('Content-type', 'application/json');
xhr.send(JSON.stringify(data));
}
</script>
</body>
</html>
複製代碼
而後咱們在 app.js 中,添加如下代碼,
// 加載 fs 模塊
const fs = require('fs');
// 其餘照舊
// 讀取login頁面
const login = router.get('/login', ctx => {
ctx.response.type = 'html';
ctx.response.body = fs.createReadStream('./demos/login.html');
}).routes();
app.use(login);
複製代碼
再執行一遍
node app.js
複製代碼
打開網址
localhost:3000/login
複製代碼
便可看到表單頁,點提交,就可看到 ajax 請求發送啦。
整個項目的結構長這樣的
謝謝您的閱覽,若是文章中有錯誤的話,請看官批評以及提醒。
參考