实现axios-跑通流程

举报
搞前端的半夏 发表于 2021/11/30 22:15:22 2021/11/30
【摘要】 大家好,我是半夏👴,一个刚刚开始写文的沙雕程序员.如果喜欢我的文章,可以关注➕ 点赞 👍 加我微信:frontendpicker,邀你进群,一起学习交流前端,成为更优秀的工程师~关注公众号:半夏话前端,了解更多前端知识!点我探索新世界! 前言我们肯定不能一开始就完全就写一个完整的axios,肯定要一点一点来,本文先实现一个简单的跑的同的版本。 准备 为了先跑通整个流程我们先来实现一个ge...

大家好,我是半夏👴,一个刚刚开始写文的沙雕程序员.如果喜欢我的文章,可以关注➕ 点赞 👍 加我微信:frontendpicker,邀你进群,一起学习交流前端,成为更优秀的工程师~关注公众号:半夏话前端,了解更多前端知识!点我探索新世界!

前言

我们肯定不能一开始就完全就写一个完整的axios,肯定要一点一点来,本文先实现一个简单的跑的同的版本。

准备

为了先跑通整个流程我们先来实现一个get

axios({
  method: 'get',
  url: '/base/get',
  params: {
    p1: 1,
    p2: 2
  }
})
函数的入口-axios
import { requestConfig } from './types/index'
import xhr from './xhr'
function axios(config: requestConfig):void {
    xhr(config) 
}

export default axios;
AJAX请求-xhr
import { requestConfig } from './types/index'
export default function xhr(requestConfig:requestConfig): void{
   const {url,method,data,params} = requestConfig
   const request = new XMLHttpRequest()
   // 这里简单的处理了参数,下文会针对get参数进行处理
   request.open(method.toUpperCase(), url+`?p=${params.p}`, true)
   request.send(null)
 }

测试

测试服务器-server.js

一个完整的库,一般会有测试,这里我们使用express搭建测试服务器

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const router = express.Router();
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use(express.static(__dirname ));
router.get('/api/test/get', function (req, res) {
  console.log(req.query.p)
  res.json({
    data: `我是 get 请求的返回结果,${req.query.p}`
  })
})
app.get('/index.html', function (req, res) {
  res.sendFile( __dirname + "/example/index.html" );
})
app.get('/get/index.html', function (req, res) {
  res.sendFile( __dirname + "/example/get/index.html" );
})
app.use(router)
const port = 4396
module.exports = app.listen(port, () => {
  console.log(`Server listening on http://localhost:${port}, Ctrl+C to stop`)
})

package.json

"test": "node server.js",

执行yarn test 启动测试服务器。

客户端-example

example/index.html -入口

<body>
    <h1>ts-axios examples</h1>
    <ul>
      <li><a href="./get/index.html">get 测试</a></li>
    </ul>
  </body>

example/get/index.html - get 测试

<body>
    <div>get</div>
    // 引入打包生成的文件,umd格式的可以直接使用
    <script src="../../dist/index.umd.js"></script>
    <script>
      axios({
        method: "get",
        url: "/api/test/get",
        params: {
         p:1
        },
      });
    </script>
  </body>
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。