1. 前后端交互模式
1.1 接口调用方式
- 原生 Ajax
- 基于 jQuery 的 Ajax
- fetch
- axios
1.2 URL地址格式
1.2.1 传统形式的URL
1. 格式:schema://host:port/path?query#fragment
schema:协议。例如http、https、ftp等。
host:域名或者IP地址。
port:端口,http默认端口80,可以省略。
path:路径,例如/abc/a/b/c。
query:查询参数,例如 uname=lisi&age=12
。
fragment:锚点(哈希Hash),用于定位页面的某个位置。
2. 符合规则的URL
http://www.itcast.cn
http://www.itcast.cn/java/web
http://www.itcast.cn/java/web?flag=1
http://www.itcast.cn/java/web?flag=1#function
1.2.2 Restful形式的URL
- HTTP请求方式:GET(查询)、POST(添加)、PUT(修改)、DELETE(删除)。
- 符合规则的URL地址
http://www.hello.com/books GET
http://www.hello.com/books POST
http://www.hello.com/books/123 PUT
http://www.hello.com/books/123 DELETE
2. Promise 用法
2.1 异步调用
- 异步效果分析:
定时任务
、Ajax
、事件函数
。 - 多次异步调用的依赖分析
- 多次异步调用的结果顺序不确定。
- 异步调用结果如果存在依赖,则需要嵌套。
2.2 Promise 概述
Promise是异步编程的一种解决方案,从语法上讲,Promise是一个对象,从它可以获取异步操作的消息。
使用Promise主要有以下好处:可以避免多层异步调用嵌套问题(回调地狱);Promise对象提供了简洁的API,使得控制异步操作更加容易。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
<body>
<div>前后端交互</div>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
/*
前后端交互-异步编程与Promise概述
*/
// var ret = '---';
// $.ajax({
// url: 'http://localhost:3000/data',
// success: function(data) {
// ret = data;
// console.log(ret)
// }
// });
// console.log(ret)
// ----------------------------
// $.ajax({
// url: 'http://localhost:3000/data',
// success: function(data) {
// console.log(data)
// }
// });
// $.ajax({
// url: 'http://localhost:3000/data1',
// success: function(data) {
// console.log(data)
// }
// });
// $.ajax({
// url: 'http://localhost:3000/data2',
// success: function(data) {
// console.log(data)
// }
// });
// -----------------------------------
// 回调地狱
$.ajax({
url: 'http://localhost:3000/data',
success: function(data) {
console.log(data)
$.ajax({
url: 'http://localhost:3000/data1',
success: function(data) {
console.log(data)
$.ajax({
url: 'http://localhost:3000/data2',
success: function(data) {
console.log(data)
}
});
}
});
}
});
</script>
</body>
2.3 Promise 基本用法
- 实例化
Promise
对象,构造函数中传递函数,该函数用于处理异步任务。 resolve
和reject
两个参数用于处理成功和失败两种情况,并通过p.then
获取处理结果,即接收并处理异步处理返回的结果。
var p = new Promise(function(resolve, reject){
// 成功时调用 resolve()
// 失败时调用 reject()
});
p.then(function(ret){
// 从resolve得到正常结果
}, function(ret){
// 从reject得到错误信息
});
<body>
<script type="text/javascript">
/*
Promise基本使用
*/
// console.log(typeof Promise)
// console.dir(Promise);
var p = new Promise(function(resolve, reject){
// 这里用于实现异步任务
setTimeout(function(){
var flag = false;
if(flag) {
// 正常情况
resolve('hello');
}else{
// 异常情况
reject('出错了');
}
}, 100);
});
p.then(function(data){
console.log(data);
},function(info){
console.log(info);
});
</script>
</body>
2.4 基于Promise
处理Ajax
请求
2.4.1 处理原生Ajax
function queryData(url) {
return new Promise(function(resolve, reject){
var xhr = new XMLHttpRequest();
// 下面的函数不止触发一次
// 只要状态发生了变化就会被触发
xhr.onreadystatechange = function(){
if(xhr.readyState != 4) return;
if(xhr.readyState == 4 && xhr.status == 200) {
// 处理正常的情况
resolve(xhr.responseText);
}else{
// 处理异常情况
reject('服务器错误');
}
};
// 准备发送前的一些参数
xhr.open('get', url);
xhr.send(null);
});
}
<body>
<script type="text/javascript">
/*
基于Promise发送Ajax请求
*/
function queryData(url) {
var p = new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState != 4) return;
if (xhr.readyState == 4 && xhr.status == 200) {
// 处理正常的情况
resolve(xhr.responseText);
} else {
// 处理异常情况
reject("服务器错误");
}
};
xhr.open("get", url);
xhr.send(null);
});
return p;
}
queryData('http://localhost:3000/data')
.then(function(data){
console.log(data);
},function(info){
console.log(info)
});
</script>
</body>
2.4.2 发送多次Ajax请求
// ============================
// 发送多个ajax请求并且保证顺序
queryData()
.then(function (data) {
console.log(data);
return queryData();
})
.then(function (data) {
console.log(data);
return queryData();
})
.then(function (data) {
console.log(data);
return queryData();
});
通过then方法把多个任务变成线性关系,这样就可以保证它们的执行顺序。then方法的参数中的函数return的是一个新的Promise实例对象,下一个then方法的调用者就是上一个then方法的参数中函数返回的Promise对象。then方法的参数中函数的参数data用于接收上一个异步任务的处理结果。
<body>
<script type="text/javascript">
/*
基于Promise发送Ajax请求
*/
function queryData(url) {
var p = new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState != 4) return;
if (xhr.readyState == 4 && xhr.status == 200) {
// 处理正常的情况
resolve(xhr.responseText);
} else {
// 处理异常情况
reject("服务器错误");
}
};
xhr.open("get", url);
xhr.send(null);
});
return p;
}
// ============================
// 发送多个ajax请求并且保证顺序
queryData("http://localhost:3000/data")
.then(function (data) {
console.log(data);
return queryData("http://localhost:3000/data1");
})
.then(function (data) {
// data 为后端返回的处理结果
console.log(data);
return queryData("http://localhost:3000/data2");
})
.then(function (data) {
console.log(data);
});
</script>
</body>
2.5 then参数中的函数返回值
2.5.1 返回Promise实例对象
返回的该实例对象会调用下一个then。
2.5.2 返回普通值
返回的普通值会直接传递给下一个then,通过then参数中函数的参数接收该值。
在该场景中,返回普通之后会产生一个默认的Promise对象,该对象用于调用下一个then方法。
<body>
<script type="text/javascript">
/*
then参数中的函数返回值
*/
function queryData(url) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState != 4) return;
if (xhr.readyState == 4 && xhr.status == 200) {
// 处理正常的情况
resolve(xhr.responseText);
} else {
// 处理异常情况
reject("服务器错误");
}
};
xhr.open("get", url);
xhr.send(null);
});
}
queryData("http://localhost:3000/data")
.then(function (data) {
return queryData("http://localhost:3000/data1");
})
.then(function (data) {
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve(123);
}, 1000);
});
})
.then(function (data) {
return "hello";
})
.then(function (data) {
console.log(data);
});
</script>
</body>
2.6 Promise常用的API
除了then方法外,Promise还提供了其他的API。
2.6.1 实例方法
p.then()
得到异步任务的正确结果。p.catch()
获取异常信息。p.finally()
成功与否都会执行(尚且不是正是标准)。
<body>
<script type="text/javascript">
/*
Promise常用API-实例方法
*/
// console.dir(Promise);
function foo() {
return new Promise(function (resolve, reject) {
setTimeout(function () {
// resolve(123);
reject("error");
}, 100);
});
}
// foo()
// .then(function(data){
// console.log(data)
// })
// .catch(function(data){
// console.log(data)
// })
// .finally(function(){
// console.log('finished')
// });
// --------------------------
// 两种写法是等效的
foo()
.then(
function (data) {
console.log(data);
},
function (data) {
console.log(data);
}
)
.finally(function () {
console.log("finished");
});
</script>
</body>
2.6.2 对象方法
Promise.all()
并发处理多个异步任务,所有任务都执行完成才能得到结果。
Promise.race()
并发处理多个异步任务,只要有一个任务完成就能到结果。
Promise.all([p1, p2, p3]).then((result) => {
console.log(result);
});
Promise.race([p1, p2, p3]).then((result) => {
console.log(result);
});
<body>
<script type="text/javascript">
/*
Promise常用API-对象方法
*/
// console.dir(Promise)
function queryData(url) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState != 4) return;
if (xhr.readyState == 4 && xhr.status == 200) {
// 处理正常的情况
resolve(xhr.responseText);
} else {
// 处理异常情况
reject("服务器错误");
}
};
xhr.open("get", url);
xhr.send(null);
});
}
var p1 = queryData("http://localhost:3000/a1");
var p2 = queryData("http://localhost:3000/a2");
var p3 = queryData("http://localhost:3000/a3");
// Promise.all([p1,p2,p3]).then(function(result){
// console.log(result)
// })
Promise.race([p1, p2, p3]).then(function (result) {
console.log(result);
});
</script>
</body>
3. 接口调用-fetch
用法
3.1 fetch
概述
3.1.1 基本特性
- 更加简单的数据获取方式,功能更强大、更灵活,可以看做是xhr的升级版。
- 基于Promise实现。
3.1.2 语法结构
fetch(url).then(fn2)
.then(fn3)
...
.catch(fn)
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
3.2 fetch
的基本用法
语法格式
fetch('/abc').then(data => {
return data.text();
}).then(ret => {
// 注意这里得到的才是最终的数据
console.log(ret);
});
实例代码
<body>
<script type="text/javascript">
/*
Fetch API 基本用法
*/
fetch("http://localhost:3000/fdata")
.then(function (data) {
// text()方法属于fetchAPI的一部分,它返回一个Promise实例对象,用于获取后台返回的数据
return data.text();
})
.then(function (data) {
console.log(data);
});
</script>
</body>
3.3 fetch
请求参数
3.3.1 常用配置选项
method(String)
:HTTP请求方法,默认为GET(GET、POST、PUT、DELETE)。body(String)
:HTTP的请求参数。headers(Object)
:HTTP的请求头,默认为{}
。
fetch('/abc', {
method: 'get'
}).then(data => {
return data.text();
}).then(ret => {
// 注意这里得到的才是最终的数据
console.log(ret);
});
3.3.2 GET请求方式的参数传递
基于传统URL形式的传参方式
// GET参数传递-传统URL
fetch('http://localhost:3000/books?id=123', {
method: 'get'
}).then(data => {
return data.text();
}).then(ret => {
// 注意这里得到的才是最终的数据
console.log(ret);
});
基于Resful形式的传参方式
// GET参数传递-restful形式的URL
fetch('http://localhost:3000/books/456', {
method: 'get'
}).then(data => {
return data.text();
}).then(ret => {
// 注意这里得到的才是最终的数据
console.log(ret);
});
3.3.3 DELETE请求方式的参数传递
// DELETE请求方式参数传递
fetch('http://localhost:3000/books/789', {
method: 'delete'
}).then(function(data){
return data.text();
}).then(function(data){
console.log(data)
});
总结:GET与DELETE方式都是通过 /
形式传参的。
3.3.4 POST请求方式的参数传递
方式一:基于"Content-Type": "application/x-www-form-urlencoded"
// POST请求传参
fetch("http://localhost:3000/books", {
method: "post",
body: "uname=lisi&pwd=123",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
}).then(function (data) {
return data.text();
}).then(function (data) {
console.log(data);
});
后台代码
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
// 处理静态资源
app.use(express.static('public'));
// 处理参数
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// 设置允许跨域访问该服务
app.all('*', function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header('Access-Control-Allow-Headers', 'Content-Type');
res.header('Access-Control-Allow-Headers', 'mytoken');
next();
});
// 路由
app.post('/books', (req, res) => {
res.send('POST请求传递参数!' + req.body.uname + '---' + req.body.pwd);
});
// 启动监听
app.listen(3000, () => {
console.log('running...');
});
方式二:基于"Content-Type": "json"
// POST请求传参
fetch('http://localhost:3000/books', {
method: 'post',
body: JSON.stringify({
uname: '张三',
pwd: '456'
}),
headers: {
'Content-Type': 'application/json'
}
})
.then(function(data){
return data.text();
}).then(function(data){
console.log(data)
});
后台代码与方式一的基本没有变化。后台代码之所以能够支持这两种方式的前台请求是由于app.use(bodyParser.json());
的bodyParser中间件提供的支持。
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
// 处理静态资源
app.use(express.static('public'));
// 处理参数
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// 设置允许跨域访问该服务
app.all('*', function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header('Access-Control-Allow-Headers', 'Content-Type');
res.header('Access-Control-Allow-Headers', 'mytoken');
next();
});
// 路由
app.post('/books', (req, res) => {
res.send('POST请求传递参数!' + req.body.uname + '---' + req.body.pwd);
});
// 启动监听
app.listen(3000, () => {
console.log('running...');
});
3.3.5 PUT请求方式的参数传递
前台代码
// PUT请求传参
fetch("http://localhost:3000/books/123", {
method: "put",
body: JSON.stringify({
uname: "张三",
pwd: "789",
}),
headers: {
"Content-Type": "application/json",
},
})
.then(function (data) {
return data.text();
})
.then(function (data) {
console.log(data);
});
后台代码
app.put('/books/:id', (req, res) => {
res.send('PUT请求传递参数!' + req.params.id + '---' + req.body.uname + '---' + req.body.pwd);
});
总结:对于POST和PUT方式的参数传递,需要通过body来传递实际的请求参数,同时还需要设置headers。headers支持json格式的数据和传统表单类型的数据,这两种数据的传递需要后台的支撑。
3.4 fetch
响应结果
响应数据格式
text()
:将返回结果处理成字符串类型。json()
:返回结果和JSON.parse(responseText)
一样。
前台代码
<script type="text/javascript">
/*
Fetch响应结果的数据格式
*/
fetch('http://localhost:3000/json').then(function(data){
// return data.json();
return data.text();
}).then(function(data){
// console.log(data.uname)
// console.log(typeof data)
var obj = JSON.parse(data);
console.log(obj.uname,obj.age,obj.gender)
})
</script>
后台处理
app.get('/json', (req, res) => {
// json为express提供的API
res.json({
uname: 'lisi',
age: 13,
gender: 'male'
});
});
4. 接口调用-axios
用法
4.1 axios
的基本特性
axios
(官网:https://github.com/axios/axios)是一个基于Promise用于浏览器和node.js的HTTP客户端。HTTP客户端可以调用HTTP格式的后台接口,它具有以下特征:
- 支持浏览器和node.js。
- 支持Promise。
- 能拦截请求和响应。
- 自动转换JSON数据。
4.2 axios
的基本用法
在使用之前需要引入对应的JS库文件。
将下载的压缩包解压,讲
\axios-master\axios-master\dist
目录下的axios.js复制到项目的根目录下,之后在使用axios的时候,引入该文件即可。
前台代码
<body>
<script type="text/javascript" src="js/axios.js"></script>
<script type="text/javascript">
axios.get("http://localhost:3000/adata").then(function (ret) {
// 注意data属性是固定的用法,用于获取后台的实际数据
// console.log(ret.data)
console.log(ret);
});
</script>
</body>
后台代码
app.get('/adata', (req, res) => {
res.send('Hello axios!');
});
4.3 axios
的常用API
- get:查询数据
- post:添加数据
- put:修改数据
- delete:删除数据
4.4 axios
的参数传递
4.4.1 GET传递参数
1. 通过传统URL传递参数
<body>
<script type="text/javascript" src="js/axios.js"></script>
<script type="text/javascript">
/*
axios请求参数传递
*/
// axios get请求传参
axios.get('http://localhost:3000/axios?id=123').then(function(ret){
console.log(ret.data)
});
</script>
</body>
后台代码
app.get('/axios', (req, res) => {
res.send('axios get 传递参数' + req.query.id);
});
2. 通过URL(Resful)传递参数
<body>
<script type="text/javascript" src="js/axios.js"></script>
<script type="text/javascript">
/*
axios请求参数传递
*/
// axios get请求传参
axios.get("http://localhost:3000/axios/123").then(function (ret) {
console.log(ret.data);
});
</script>
</body>
后台代码
app.get('/axios/:id', (req, res) => {
res.send('axios get (Restful) 传递参数' + req.params.id);
});
3. 通过params
选项传递参数
<body>
<script type="text/javascript" src="js/axios.js"></script>
<script type="text/javascript">
/*
axios请求参数传递
*/
// axios get请求传参
axios
.get("http://localhost:3000/axios", {
params: {
id: 789,
},
})
.then(function (ret) {
console.log(ret.data);
});
</script>
</body>
后台代码
app.get('/axios', (req, res) => {
res.send('axios get 传递参数' + req.query.id);
});
4.4.2 DELETE传递参数
DELETE参数传递方式与GET类似,此处只类举第三种。
<body>
<script type="text/javascript" src="js/axios.js"></script>
<script type="text/javascript">
/*
axios请求参数传递
*/
// axios delete 请求传参
axios
.delete("http://localhost:3000/axios", {
params: {
id: 111,
},
})
.then(function (ret) {
console.log(ret.data);
});
</script>
</body>
后台代码
app.delete('/axios', (req, res) => {
res.send('axios get 传递参数' + req.query.id);
});
4.4.3 POST传递参数
1. 通过选项传递参数( 默认传递的是json格式的数据
)。
// axios post 请求传参
axios
.post("http://localhost:3000/axios", {
uname: "lisi",
pwd: 123,
})
.then(function (ret) {
console.log(ret.data);
});
后台代码
app.post('/axios', (req, res) => {
res.send('axios post 传递参数' + req.body.uname + '---' + req.body.pwd);
});
2. 通过URLSearchParams
传递参数( application/x-www-form-urlencoded
)。
// axios post 请求传参
var params = new URLSearchParams();
params.append("uname", "zhangsan");
params.append("pwd", "111");
axios.post("http://localhost:3000/axios", params).then(function (ret) {
console.log(ret.data);
});
后台代码
app.post('/axios', (req, res) => {
res.send('axios post 传递参数' + req.body.uname + '---' + req.body.pwd);
});
4.4.4 PUT传递参数
参数传递方式与POST类似,两种方法都支持。
// axios put 请求传参
axios
.put("http://localhost:3000/axios/123", {
uname: "lisi",
pwd: 123,
})
.then(function (ret) {
console.log(ret.data);
});
后台代码
app.put('/axios/:id', (req, res) => {
res.send('axios put 传递参数' + req.params.id + '---' + req.body.uname + '---' + req.body.pwd);
});
4.4.5 参数传递总结
对于axios发送POST和PUT请求来说,它们都支持两个格式的参数传递,一种是json格式的数据,另一种是传统表单行式的数据。具体用哪种取决于后台。
1. get和 delete请求传递参数
- 通过传统的url 以 ? 的形式传递参数
- restful 形式传递参数
- 通过params 形式传递参数
2. post 和 put 请求传递参数
- 通过选项传递参数
- 通过 URLSearchParams 传递参数
4.5 axios
的响应结果
响应结果的主要属性
- data:实际响应回来的数据。
- headers:响应头信息。
- status:响应状态码。
- statusText:响应状态信息。
4.6 axios
的全局配置
- 超时时间:
axios.defaults.timeout = 3000;
- 默认地址:
axios.defaults.baseURL = "http://localhost:3000/app";
- 设置请求头:
axios.defaults.headers["mytoken"] = "aqwerwqwerqwer2ewrwe23eresdf23";
<body>
<script type="text/javascript" src="js/axios.js"></script>
<script type="text/javascript">
/*
axios 响应结果与全局配置
*/
// axios.get('http://localhost:3000/axios-json').then(function(ret){
// console.log(ret.data.uname)
// })
// 配置请求的基准URL地址
axios.defaults.baseURL = "http://localhost:3000/";
// 配置请求头信息
axios.defaults.headers["mytoken"] = "hello";
axios.get("axios-json").then(function (ret) {
console.log(ret.data.uname);
});
</script>
</body>
后台代码
app.get('/axios-json', (req, res) => {
res.json({
uname: 'lisi',
age: 12
});
});
4.7 axios
拦截器
4.7.1 请求拦截器
在请求发出之前设置一些信息
// 添加一个请求拦截器
axios.interceptors.request.use(
function (config) {
// 在请求发出之前进行一些信息设置
console.log(config.url);
config.headers.mytoken = "nihao";
return config;
},
function (err) {
// 处理相应的错误信息
console.log(err);
}
);
4.7.2 相应拦截器
在获取数据之前对数据做一些加工处理。
// 添加一个响应拦截器
axios.interceptors.response.use(
function (res) {
// 在这里对返回的数据进行处理
// console.log(res);
var data = res.data;
return data;
},
function (err) {
// 处理相应的错误信息
console.log(err);
}
);
<body>
<script type="text/javascript" src="js/axios.js"></script>
<script type="text/javascript">
/*
axios拦截器
*/
axios.interceptors.request.use(
function (config) {
console.log(config.url);
config.headers.mytoken = "nihao";
return config;
},
function (err) {
console.log(err);
}
);
axios.interceptors.response.use(
function (res) {
// console.log(res)
var data = res.data;
return data;
},
function (err) {
console.log(err);
}
);
axios.get("http://localhost:3000/adata").then(function (data) {
console.log(data);
});
</script>
</body>
5. 接口调用async
/await
用法
5.1 async
/await
的基本用法
async/await
是ES7引入的新语法,可以更加方便地进行异步操作。async
关键字用于函数上(async
函数的返回值是Promise
实例对象)。await
关键字用于async
函数当中(await
可以得到异步的结果)。
<script type="text/javascript" src="js/axios.js"></script>
<script type="text/javascript">
/*
async/await 处理异步操作:
async函数返回一个Promise实例对象
await后面可以直接跟一个 Promise实例对象
*/
axios.defaults.baseURL = 'http:localhost:3000';
// axios.get('adata').then(function(ret){
// console.log(ret.data)
// })
// async function queryData() {
// var ret = await axios.get('adata');
// // console.log(ret.data)
// return ret.data;
// }
async function queryData() {
var ret = await new Promise(function(resolve, reject){
setTimeout(function(){
resolve('nihao')
},1000);
})
// console.log(ret.data)
return ret;
}
queryData().then(function(data){
console.log(data)
})
</script>
5.2 async
/await
处理多个异步请求
5.2.1 多个异步请求的场景
<body>
<script type="text/javascript" src="js/axios.js"></script>
<script type="text/javascript">
/*
async/await处理多个异步任务
*/
axios.defaults.baseURL = "http://localhost:3000";
async function queryData() {
var info = await axios.get("async1");
var ret = await axios.get("async2?info=" + info.data);
return ret.data;
}
queryData().then(function (data) {
console.log(data);
});
</script>
</body>
后台代码
app.get('/async1', (req, res) => {
res.send('hello1');
});
app.get('/async2', (req, res) => {
if (req.query.info == 'hello') {
res.send('world');
} else {
res.send('error');
}
});
本章用到的后台代码汇总
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
// 处理静态资源
app.use(express.static('public'));
// 处理参数
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// 设置允许跨域访问该服务
app.all('*', function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header('Access-Control-Allow-Headers', 'Content-Type');
res.header('Access-Control-Allow-Headers', 'mytoken');
next();
});
app.get('/async1', (req, res) => {
res.send('hello1');
});
app.get('/async2', (req, res) => {
if (req.query.info == 'hello') {
res.send('world');
} else {
res.send('error');
}
});
app.get('/adata', (req, res) => {
res.send('Hello axios!');
});
app.get('/axios', (req, res) => {
res.send('axios get 传递参数' + req.query.id);
});
app.get('/axios/:id', (req, res) => {
res.send('axios get (Restful) 传递参数' + req.params.id);
});
app.delete('/axios', (req, res) => {
res.send('axios get 传递参数' + req.query.id);
});
app.post('/axios', (req, res) => {
res.send('axios post 传递参数' + req.body.uname + '---' + req.body.pwd);
});
app.put('/axios/:id', (req, res) => {
res.send('axios put 传递参数' + req.params.id + '---' + req.body.uname + '---' + req.body.pwd);
});
app.get('/axios-json', (req, res) => {
res.json({
uname: 'lisi',
age: 12
});
});
app.get('/fdata', (req, res) => {
res.send('Hello Fetch!');
});
app.get('/books', (req, res) => {
res.send('传统的URL传递参数!' + req.query.id);
});
app.get('/books/:id', (req, res) => {
res.send('Restful形式的URL传递参数!' + req.params.id);
});
app.delete('/books/:id', (req, res) => {
res.send('DELETE请求传递参数!' + req.params.id);
});
app.post('/books', (req, res) => {
res.send('POST请求传递参数!' + req.body.uname + '---' + req.body.pwd);
});
app.put('/books/:id', (req, res) => {
res.send('PUT请求传递参数!' + req.params.id + '---' + req.body.uname + '---' + req.body.pwd);
});
app.get('/json', (req, res) => {
res.json({
uname: 'lisi',
age: 13,
gender: 'male'
});
});
app.get('/a1', (req, res) => {
setTimeout(function () {
res.send('Hello TOM!');
}, 1000);
});
app.get('/a2', (req, res) => {
setTimeout(function () {
res.send('Hello JERRY!');
}, 2000);
});
app.get('/a3', (req, res) => {
setTimeout(function () {
res.send('Hello SPIKE!');
}, 3000);
});
// 路由
app.get('/data', (req, res) => {
res.send('Hello World!');
});
app.get('/data1', (req, res) => {
setTimeout(function () {
res.send('Hello TOM!');
}, 1000);
});
app.get('/data2', (req, res) => {
res.send('Hello JERRY!');
});
// 启动监听
app.listen(3000, () => {
console.log('running...');
});