最近在学习ES6的相关知识,看完了Promise,于是打算用Promise实现一个原生JS的Ajax例子,顺便复习一下Node的相关知识。
后端使用的是Express框架,具体步骤如下:
npm init
初始化,这个就一直下一步就行了,需要注意的是项目文件夹名不能为中文。
npm install express --save
使用
npm
安装express
。
node_modules/ package.json package-lock.json
server.js
,和上面的文件同级。node_modules/ package.json package-lock.json server.js
直接看代码:
code:
const express = require('express');
const http = require('http');
const bodyParser = require('body-parser');
const app = new express();
// 创建 json 解析
app.use(bodyParser.json());
// 创建 application/x-www-form-urlencoded 编码解析
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static('public'));
const server = app.listen(3000, () => {
const host = server.address().address;
const port = server.address().port;
console.log('app listening at http://%s:%s', host, port);
});
let data = [
{ name: 'zhangsan', age: 23 },
{ name: 'lisi', age: 24 },
{ name: 'wangwu', age: 26 },
{ name: 'zhaoliu', age: 27 },
{ name: 'tianqi', age: 29 }
];
app.get('/gettest', (req, res) => {
console.log(req.body);
res.status(200),
res.json(data)
});
app.post('/posttest', function(req, res) {
console.log(req.body);
res.status(200),
res.json(data)
});
在代码中写了两个处理请求的方法:
/gettest
:处理get请求/posttest
:处理post请求代码挺简单的,就不一一解释了。
执行:
node server.js
,启动服务 使用浏览器访问:http://localhost:3000/
此时可以看见页面中返回了在server中定义的data
里面的数据:
[
{ name: 'zhangsan', age: 23 },
{ name: 'lisi', age: 24 },
{ name: 'wangwu', age: 26 },
{ name: 'zhaoliu', age: 27 },
{ name: 'tianqi', age: 29 }
];
后台搞定了,接下来是本文的重头戏,撸前端。
因为后端指定了静态文件在public
,于是我们新建index.html
文件,放在public
文件夹下。public
文件夹和server.js
同级。
此时的目录结构是这样的:
│ package-lock.json
│ package.json
│ server.js
│
├─node_modules
└─public
index.html
在index.html
中开始撸Promise
code:
<!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>Document</title>
</head>
<body>
<script>
const myAjax = function(data, url) {
console.log(data);
console.log(url);
const promise = new Promise((resolve, reject) => {
const stateChange = function() {
if (this.readyState !== 4) {
return;
}
if (this.status === 200) {
resolve(this.response);
} else {
reject(new Error(this.statusText));
}
};
const myHttp = new XMLHttpRequest();
myHttp.open('POST', url, 'true');
myHttp.onreadystatechange = stateChange;
myHttp.responseType = 'json';
myHttp.setRequestHeader('Content-Type', 'application/json');
myHttp.send(JSON.stringify(data));
});
return promise;
};
let data = {
user: 'root'
};
let url = 'http://localhost:3000/posttest';
myAjax(data, url).then(res => {
console.log(res);
}).catch(err => {
console.log(err);
});
</script>
</body>
</html>
此处是使用Promise
写的Ajax
的POST
请求,GET
请求就不写了。Promise
还是挺好用的。