vue3+vite project configuration axios and cross-domain

Table of contents

install axios

package request

global reference

Configure cross-domain

request test

Test Results


After tossing a few times, I finally managed to record it. 

Vite creates a vue3 project, so I won’t go into details. You can read this blog (with router and vuex installation)

install axios

npm install axios

package request

Here is the newly created js file package under src/assets/js, when citing it should be quoted from here

If you are not going to use the qs library, you don’t need to install it, just modify the places used in the code

I am not good at encapsulation, so here is a random copy from the Internet.

If you have seen the packaging content of the advanced point, please send me a link, thank you

import axios from "axios";
import qs from "qs";


axios.defaults.baseURL = '' 

//post请求头
axios.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded;charset=UTF-8";
//设置超时
axios.defaults.timeout = 10000;

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

axios.interceptors.response.use(
    response => {
        if (response.status == 200) {
            return Promise.resolve(response);
        } else {
            return Promise.reject(response);
        }
    },
    error => {

        console.log(error);
    }
);
export default {
    post(url, data) {
        return new Promise((resolve, reject) => {
            axios({
                    method: 'post',
                    url,
                    data: qs.stringify(data),
                })
                .then(res => {
                    resolve(res.data)
                })
                .catch(err => {
                    reject(err)
                });
        })
    },

    get(url, data) {
        return new Promise((resolve, reject) => {
            axios({
                    method: 'get',
                    url,
                    params: data,
                })
                .then(res => {
                    resolve(res.data)
                })
                .catch(err => {
                    reject(err)
                })
        })
    }
};

global reference

Modify main.js

Damn, I wrote the wrong order when I did the mount here. I did a global mount before declaring the app. I didn’t figure it out for hours.

import { createApp } from 'vue'
import App from './App.vue'
import axios from "./assets/lib/axios";


const app = createApp(App)
app.config.globalProperties.$h = axios;
app.mount('#app')

Configure cross-domain

Modify the vite.config.js file

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  server: {
      host: '0.0.0.0',
      port: 8080,
      proxy: {
        '/api': {
          target: '实际请求地址',	//实际请求地址
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, '')
        },
      }
    }
})

request test

Because it's just a test, it's directly operated on the app.vue page

<template>
	<img alt="Vue logo" src="./assets/logo.png" />
	<HelloWorld msg="Hello Vue 3 + Vite" /> 
</template>

<script>
	import HelloWorld from './components/HelloWorld.vue'
	export default {
		mounted() {
			this.$h.get(`api/接口地址`).then(res => {
				console.log(res)
			})
		}
	}
</script>

<style>
	#app {
		font-family: Avenir, Helvetica, Arial, sans-serif;
		-webkit-font-smoothing: antialiased;
		-moz-osx-font-smoothing: grayscale;
		text-align: center;
		color: #2c3e50;
		margin-top: 60px;
	}
</style>

Test Results

Guess you like

Origin blog.csdn.net/shinjie1210/article/details/119901055