目录

Vue使用axios实现跨域

# request.js

import axios from 'axios'


export function request(config) {
  // 1.创建axios的实例
  const instance = axios.create({
    // 设置基础的url配置项,这样接口处的url前面就不用写url:'http://127.0.0.1:8000/api/home',直接写成 url:'/api/home', 就可以了
    // baseURL: 'https://interface.sina.cn',
    baseURL: '/api', //重点
    //设置请求超时时间
    timeout: 5000
  })

  // 2.axios的拦截器,用不到的可以忽略这节
  // 2.1.请求拦截的作用
  // instance.interceptors.request.use(config => {
  //   return config
  // }, err => {
  //   console.log('请求拦截err: '+err);
  // })
  //
  // // 2.2.响应拦截
  // instance.interceptors.response.use(res => {
  //   return res.data
  // }, err => {
  //       console.log('响应拦截err: '+err);
  // })

  // 3.发送真正的网络请求
  return instance(config)
}
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

# newwork.js

// 导入封装好的Axios
import {request} from './request' //注意request.js的相对路径问题

// const tokens = JSON.parse(localStorage.getItem('sutuofeng_login_info')).token
// console.log(tokens,89898)

export function getdata(tokens) {
  return request({
    url:'/news/wap/fymap2020_data.d.json',
    method:'get',
  })
}
1
2
3
4
5
6
7
8
9
10
11
12

# * vue.config.js

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  devServer: {
    open: true, //是否自动弹出浏览器页面
    host: "localhost", //前端服务器ip
    port: '8080', //前端服务器端口  
    //跨域代理
    //把/api替换为https://interface.sina.cn
    proxy: {
      '/api': {
        target: 'https://interface.sina.cn', //请求的API服务器的地址
        //开启跨域
        changeOrigin: true,
        pathRewrite: {
          '^/api': 'https://interface.sina.cn'
        }
      }
    }
  }
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# 原理:

因为我们给url加上了前缀 /api,我们访问/news/wap/fymap2020_data.d.json就当于访问了:/api/news/wap/fymap2020_data.d.json

又因为在vue.config.js 中的 proxy中拦截了 /api ,并把 /api 及其前面的所有替换成了 target 中的内容,因此实际访问 Url 是https://interface.sina.cn/news/wap/fymap2020_data.d.json

中间进行一步转换api操作,实际上就是来一手回首掏“骗过”浏览器检测跨域的操作,代理让浏览器以为我们访问/api/news/wap/fymap2020_data.d.json,实则是https://interface.sina.cn/news/wap/fymap2020_data.d.json

上次更新: 2023/09/05 17:45:42
最近更新
01
关于我
07-14
02
科学上网
11-15
03
OSS+CDN
09-23
更多文章>
极昼青春
买辣椒也用券