本文介绍: config.headers[“Authorization”] = Token ${sessionStorage.getItem(‘token’)}“: 如果 ‘token’ 存在,这行代码将添加一个名为 ‘Authorization’ 的请求头,其值为 ‘Token’ 后跟用户的身份验证令牌。这是常见的身份验证方式,用于向服务器证明客户端有权访问受保护的资源。
  1. 安装axios:

    使用 npm:

    npm install axios

    使用 yarn:

    yarn add axios
  2. 在src目录下创建一个新的文件夹api,然后在此文件夹下创建一个axios.ts文件.

    import axios from "axios";
    
    const http = axios.create({
      baseURL:'http://www....../api/'
    })
    
    // 添加请求拦截器
    http.interceptors.request.use(function (config) {
      // 在发送请求之前做些什么
      if (sessionStorage.getItem('token')) {
       config.headers["Authorization"] = `Token ${sessionStorage.getItem('token')}`
      }
      return config;
    }, function (error) {
      // 对请求错误做些什么
      return Promise.reject(error);
    });
    
    // 添加响应拦截器
    http.interceptors.response.use(function (response) {
      // 对响应数据做点什么
      return response;
    }, function (error) {
      // 对响应错误做点什么
      return Promise.reject(error);
    });
    
    export default http
  3. 在main.ts文件中

    import http from '@/api/axios';
    app.config.globalProperties.$http = http
  4. 组件中调用

    <script lang="ts" setup>
    import { onMounted } from 'vue';
    import { getCurrentInstance } from 'vue'
    const { proxy }: any = getCurrentInstance()
    
    
    const getImage = async () => {
           
        await proxy.$http.post('http://www.../api/api-token-auth', {
            username: 'admin',
            password: '123456'
        }).then((res: any) => {
    
            // console.log(res.data)
            sessionStorage.setItem('token', res.data.token)
        }).catch((error: string) => {
            console.log('失败了');
    
            console.log(error)
        })
    
        await proxy.$http.get('http://www.../api/materials').then((res: any) => {
            console.log(res);
    
        }).catch((error: string) => {
            console.log('失败了');
    
            console.log(error)
        })
    }
    
    
    onMounted(() => {
        getImage();
    })
    
    
    
    </script>

原文地址:https://blog.csdn.net/H2608520347/article/details/135594437

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。

如若转载,请注明出处:http://www.7code.cn/show_56432.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注