接口调用方式
- 原生ajax
- 基于jQuery的ajax
- fetch
- axios
这里主要讲一下fetch和axios
fetch
- Fetch API是新的ajax解决方案 Fetch会返回Promise
- fetch不是ajax的进一步封装,而是原生js,没有使用XMLHttpRequest对象。
- fetch(url, options).then()
<script type="text/javascript">
/*
Fetch API 基本用法
fetch(url).then()
第一个参数请求的路径 Fetch会返回Promise 所以我们可以使用then 拿到请求成功的结果
*/
fetch('http://localhost:3000/fdata').then(function(data){
// text()方法属于fetchAPI的一部分,它返回一个Promise实例对象,用于获取后台返回的数据
return data.text();
}).then(function(data){
// 在这个then里面我们能拿到最终的数据
console.log(data);
})
</script>
客户端需要接口
const express = require("express");
const app = express();
const path = require("path");
const bodyParser = require("body-parser");
app.use(express.static(path.join(__dirname, "")));
app.use(bodyParser.urlencoded({
extended: false }));
app.use(bodyParser.json());
//设置允许跨域访问该服务
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("hello");
});
app.get("/async2", (req, res) => {
if (req.query.info == "hello") res.send("word");
else {
res.send("error")