Vue3跨域问题

1. vue.config.js中配置:

备注:vue.config.js 中不需要进行 pathRewrite 配置,否则重写路径后又会出现请求路径找不到的问题

const {defineConfig} = require('@vue/cli-service')
module.exports = defineConfig({
    transpileDependencies: true,
    configureWebpack: {
        devServer: {
            proxy: {
                "/api": {
                    target: "http://image.local/",
                    changeOrigin: true,
                    ws: true, //websocket
                },
            },
        },
    },
});

2. 可对 axios 进行简单的封装(在 src 目录下新建 utils/index.js):

import axios from "axios";
import { ElMessage } from 'element-plus';

const http = axios.create({
    baseURL: '/api', //设置 baseURL
    timeout: 50000,
    headers: {'Content-Type': 'application/json'},
})

http.interceptors.request.use((config) => {
    return config;
}, (error) => {
    return Promise.reject(error);
});

http.interceptors.response.use((res) => {
    const data = res.data;
    if (res.status === 200) {
        // const code = data.code;
        return Promise.resolve(data);
    }
}, (error) => {
    if (error.response.status) {
        switch (error.response.status) {
            case 404:
                ElMessage({
                    type: 'error',
                    message: '请求路径找不到!',
                    showClose: true
                });
                break;
            case 502:
                ElMessage({
                    type: 'error',
                    message: '服务器内部报错!',
                    showClose: true
                });
                break;
            default:
                break;
        }
    }
    return Promise.reject(error);
});
export default http;

3. 封装接口(在 src 目录下新建 api/index.js):

//引入封装好的 axios
import http from '../utils/https';

//对接口进行封装
const requests = {
    userLogin(params) {
        return http.post('/login', params);
    },
    ...
}

export default { requests }

4. 在 main.js 中进行挂载:

import {createApp} from 'vue'
import App from './App.vue'
import api from './api/index'

const app = createApp(App);
app.mout('#app')
app.provide('$api',api)

5. 在页面中使用:

<script>
import { inject } from "vue";

export default {
  setup(){
    const $api = inject("$api");
    $api.requests.userLogin(params).then((res) => {
      console.log(res)
    })
  }
}

</script>

猜你喜欢

转载自blog.csdn.net/weixin_57092157/article/details/129399358
今日推荐