目录

🌗 实现权限相关功能

# 需求分析

有时候需要发送一些跨域请求。默认情况下,浏览器会根据同源策略限制这种跨域请求,但是可以通过 CORS 技术解决跨域问题。

在同域的情况下,发送请求会默认携带当前域下的 Cookie,但是在跨域的情况下,默认下不会携带请求域下的 Cookie。

例如, http://domain-a.com 发送一个 http://api.domain-b.com/get 的请求,默认是不会携带 api.domain-b.com 域下的 Cookie。

如果想携带,只需要设置请求的 xhr 对象的 withCredentialstrue 即可。

# 代码实现

修改 AxiosRequestConfig 的类型定义,在 src/types/index.ts 中:

export interface AxiosRequestConfig {
  // ...
  
  withCredentials?: boolean
}
1
2
3
4
5

添加一个 withCredentials 的标志。

修改请求发送前的逻辑, src/core/xhr.ts

export default function xhr(config: AxiosRequestConfig): AxiosPromise {
  return new Promise((resolve, reject) => {
    const { /* ... */ withCredentials} = config

    //...
    
    if(withCredentials) {
      request.withCredentials = true
    }
    
    // ...
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13

# 编写测试 DEMO

/examples/more/app.ts

import axios from '../../src'

axios.get('/more/get').then(res => {
  console.log(res)
})

axios
  .post(
    'http://127.0.0.1:8088/more/server2',
    {},
    {
      withCredentials: true
    }
  )
  .then(res => {
    console.log(res)
  })
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

配置 examples/server.jsrouter

router.get('/more/get',function(req,res){
  res.json(req.cookies)
})
1
2
3

为了测试跨域发送请求,创建新的一个 server2.js 跨域服务。

const express = require('express')
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')

const app = express()

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

const router = express.Router()

const cors = {
  'Access-Control-Allow-Origin': 'http://localhost:8080',
  'Access-Control-Allow-Credentials': true,
  'Access-Control-Allow-Methods': 'POST, GET, PUT, DELETE, OPTIONS',
  'Access-Control-Allow-Headers': 'Content-Type'
}

router.post('/more/server2', function(req,res) {
  res.set(cors)
  res.json(req.cookies)
})

router.options('/more/server2', function(req,res){
  res.set(cors)
  res.end()
})

app.use(router)

const port = 8080
module.exports = app.listen(port)
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

为了携带 cookie,需要安装 cookie-parser

通过 demo 演示可以发现,对于同域请求,会携带 cookie;而对于跨域请求,只有配置了 withCredentials 为 true,才会携带 cookie。

📢 上次更新: 2022/09/02, 10:18:16