withCredentials

需求分析

有些时候我们会发一些跨域请求,比如 http://domain-a.com 站点发送一个 http://api.domain-b.com/get 的请求,默认情况下,浏览器会根据同源策略限制这种跨域请求,但是可以通过 CORS 技术解决跨域问题。

在同域的情况下,我们发送请求会默认携带当前域下的 cookie,但是在跨域的情况下,默认是不会携带请求域下的 cookie 的,比如 http://domain-a.com 站点发送一个 http://api.domain-b.com/get 的请求,默认是不会携带 api.domain-b.com 域下的 cookie,如果我们想携带(很多情况下是需要的),只需要设置请求的 xhr 对象的 withCredentials 为 true 即可。

代码实现

先修改 AxiosRequestConfig 的类型定义。

types/index.ts

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

然后修改请求发送前的逻辑。

core/xhr.ts

  1. const { /*...*/ withCredentials } = config
  2. if (withCredentials) {
  3. request.withCredentials = true
  4. }

demo 编写

examples 目录下创建 more 目录,在 cancel 目录下创建 index.html:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8">
  5. <title>More example</title>
  6. </head>
  7. <body>
  8. <script src="/__build__/more.js"></script>
  9. </body>
  10. </html>

接着创建 app.ts 作为入口文件:

  1. import axios from '../../src/index'
  2. document.cookie = 'a=b'
  3. axios.get('/more/get').then(res => {
  4. console.log(res)
  5. })
  6. axios.post('http://127.0.0.1:8088/more/server2', { }, {
  7. withCredentials: true
  8. }).then(res => {
  9. console.log(res)
  10. })

这次我们除了给 server.js 去配置了接口路由,还创建了 server2.js,起了一个跨域的服务。

  1. const express = require('express')
  2. const bodyParser = require('body-parser')
  3. const cookieParser = require('cookie-parser')
  4. const app = express()
  5. app.use(bodyParser.json())
  6. app.use(bodyParser.urlencoded({ extended: true }))
  7. app.use(cookieParser())
  8. const router = express.Router()
  9. const cors = {
  10. 'Access-Control-Allow-Origin': 'http://localhost:8080',
  11. 'Access-Control-Allow-Credentials': true,
  12. 'Access-Control-Allow-Methods': 'POST, GET, PUT, DELETE, OPTIONS',
  13. 'Access-Control-Allow-Headers': 'Content-Type'
  14. }
  15. router.post('/more/server2', function(req, res) {
  16. res.set(cors)
  17. res.json(req.cookies)
  18. })
  19. router.options('/more/server2', function(req, res) {
  20. res.set(cors)
  21. res.end()
  22. })
  23. app.use(router)
  24. const port = 8088
  25. module.exports = app.listen(port)

这里需要安装一下 cookie-parser 插件,用于请求发送的 cookie。

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

至此我们的 withCredentials feature 开发完毕,下一节课我们来实现 axios 对 XSRF 的防御功能。