实现axios-跑通流程

262 阅读1分钟

小知识,大挑战!本文正在参与「程序员必备小知识」创作活动​​

前言

我们肯定不能一开始就完全就写一个完整的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>