目录

🌒 实现基础请求

# 利用 XMLHttpRequest 发送请求

创建一个 xhr.ts 文件,导出一个 xhr 方法,接收 config 参数。并且在其中使用 XHLHttpRequest 构造器创建请求实例,从 config 获取相关请求信息:

import { AxiosRequestConfig } from './types'

export default function xhr(config: AxiosRequestConfig) {
  const { data = null, url, method = 'get' } = config

  const request = new XMLHttpRequest()

  request.open(method.toUpperCase(), url, true)

  request.send(data)
}
1
2
3
4
5
6
7
8
9
10
11

然后在入口文件中引入 xhr 模块:

import { AxiosRequestConfig } from './types'
import xhr from './xhr'

function axios(config: AxiosRequestConfig) {
  xhr(config)
}

export default axios
1
2
3
4
5
6
7
8

# DEMO 服务

安装相关依赖:

  • webpack 是打包构建工具;
  • webpack-dev-middlewarewebpack-hot-middleware 是 2 个 expresswebpack 中间件;
  • ts-loadertslint-loaderwebpack 需要的 TypeScript 相关 loader, express 是 Node.js 的服务端框架, body-parserexpress 的一个中间件,解析 body 数据用的。

examples 目录下:

创建 webpack 配置文件:

  • 会在 examples 目录下建多个子目录;会把不同章节的 demo 放到不同的子目录中,每个子目录的下会创建一个 app.tsapp.ts 作为 webpack 构建的入口文件; entries 收集了多目录个入口文件,并且每个入口还引入了一个用于热更新的文件, entries 是一个对象, key 为目录名;
  • output :根据不同的目录名称,打包生成目标 js ,名称和目录名一致。
const fs = require('fs')
const path = require('path')
const webpack = require('webpack')

module.exports = {
  mode: 'development',

  entry: fs.readdirSync(__dirname).reduce((entries, dir) => {
    const fullDir = path.join(__dirname, dir)
    const entry = path.join(fullDir, 'app.ts')
    if (fs.statSync(fullDir).isDirectory() && fs.existsSync(entry)) {
      entries[dir] = ['webpack-hot-middleware/client', entry]
    }

    return entries
  }, {}),

  output: {
    path: path.join(__dirname, '__build__'),
    filename: '[name].js',
    publicPath: '/__build__'
  },

  module: {
    rules: [
      {
        test: /\.ts$/,
        enforce: 'pre',
        use: [{ loader: 'tslint-loader' }]
      },
      {
        test: /\.tsx?$/,
        options: {
          transpileOnly: true
        }
      }
    ]
  },

  resolve: {
    extensions: ['.ts', '.tsx', '.js']
  },

  plugins: [new webpack.HotModuleReplacementPlugin(), new webpack.NoEmitOnErrorsPlugin()]
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45

创建 server.js 文件:

点击查看
const express = require('express')
const bodyParser = require('body-parser')
const webpack = require('webpack')
const webpackDevMiddleware = require('webpack-dev-middleware')
const webpackHotMiddleware = require('webpack-hot-middleware')
const WebpackConfig = require('./webpack.config')

const app = express()
const complier = webpack(WebpackConfig)

app.use(
  webpackDevMiddleware(complier, {
    publicPath: '/__build__/',
    stats: {
      colors: true,
      chunks: false
    }
  })
)

app.use(webpackHotMiddleware(complier))

app.use(express.static(__dirname))

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))

const port = process.env.PORT || 8080
module.exports = app.listen(port, ()=> {
  console.log('Server listening on http://localhost:${port}, Ctrl+C to stop')
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

创建 index.html / global.css ,作为入口文件与全局样式文件:

<!DOCTYPE html>
<html lang='en'>
<head>
  <meta charset='UTF-8'>
  <title>axios-typescript example</title>
</head>
<body style='padding: 0 20px'>
<h1>examples</h1>
<ul>
  <li><a href='simple'>Simple</a></li>
</ul>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
html, body {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
  color: #2c3e50;
}

ul {
  line-height: 1.5em;
  padding-left: 1.5em;
}

a {
  color: #7f8c8d;
  text-decoration: none;
}

a:hover {
  color: #4fc08d;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

examples 目录下创建 simple 目录,作为本章节的 demo 目录,在该目录下再创建 index.htmlapp.ts 文件:

<!DOCTYPE html>
<html lang='en'>
<head>
  <meta charset='UTF-8'>
  <title>simple example</title>
</head>
<body>

<script src="/__build__/simple.js"></script>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
import axios from '../../src/index'

axios({
  method: 'get',
  url: 'simple/get',
  params: {
    a: 1,
    b: 2
  }
})
1
2
3
4
5
6
7
8
9
10

因为我们这里通过 axios 发送了请求,那么我们的 server 端要实现对应的路由接口,我们来修改 server.js ,添加如下代码:

const router = express.Router()

router.get('/simple/get', function(req,res) {
  res.json({
    msg: 'hello world'
  })
})

app.use(router)
1
2
3
4
5
6
7
8
9

在项目 package.json 添加运行 npm run scripts

"dev": "node examples/server.js"
1
📢 上次更新: 2022/09/02, 10:18:16