四种接口调用方式

这篇博客探讨了四种接口调用方式:原生ajax、jQuery的ajax、fetch和axios。重点讲述了fetch和axios的使用,包括fetch的HTTP请求、响应格式,以及axios的基础用法、全局配置和拦截器功能。同时提到了async/await在处理异步操作中的应用。
摘要由CSDN通过智能技术生成

接口调用方式

  • 原生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")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值