真实的接口地址:http://www.liulongbin.top:300...
axios封装:
// src/request/axios.js
import axios from 'axios'
import qs from 'qs'
let api_base_url = ''
if (import.meta.env.MODE === 'development') {
api_base_url = 'http://www.liulongbin.top:3006/'
} else if (import.meta.env.MODE === 'production') {
api_base_url = 'http://www.liulongbin.top:3006/'
}
let instance = axios.create({
timeout: 1000 * 80,
baseURL: api_base_url
})
instance.defaults.responseType = 'json'
instance.defaults.withCredentials = true
instance.defaults.transformRequest = [
data => {
return qs.stringify(data)
}
]
instance.defaults.validateStatus = function () {
// return status >= 200 && status < 400; // 200- 399 resolve 其他状态码 reject
// 如果在响应拦截设置了状态码判断,这里设置返回 true
return true
}
// 请求拦截器
instance.interceptors.request.use(
config => {
//{url: "/slides", method: "get", headers: {…}, baseURL: "http://api.hzwlb.org", transformRequest: Array(1), responseType: "json",…}
return config
},
error => {
console.log('请求超时!');
return Promise.reject(error)
}
)
// 响应拦截器即异常处理
// 服务器 Response 对象
instance.interceptors.response.use(
response => {
// {data: {…}, status: 200, statusText: "OK", headers: {…}, config: {…}, request:{…}}
let data = response.data //响应的数据部分
console.log('响应数据:', data);
let status = response.status //标准状态码
if (status === 200) { //如果响应正常则放行 数据
return Promise.resolve(data) // *响应拦截器,只取数据部分*
}
else if (status >= 400 && status <= 499) {
console.log('客户端请求错误码:', status);
return
}
else {
//其他错误
console.log('服务器错误,错误码:', status);
return Promise.reject(response)
}
},
error => {
console.log('响应错误信息:')
console.log(error)
}
)
let api = {}
api.get = function (url) {
return new Promise((resolve, reject) => {
instance
.get(url)
.then(response => {
resolve(response)
})
.catch(error => {
reject(error)
})
})
}
api.post = function (url, data) {
return new Promise((resolve, reject) => {
instance
.post(url, data)
.then(response => {
resolve(response)
})
.catch(error => {
reject(error)
})
})
}
export default api
API:
// src/request/api.js
import api from "./axios.js"
export const getBooks = () => api.get('/agent/api/getbooks')
vite配置:
//vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
// 跨域
server: {
cors: true, // 默认启用并允许任何源
proxy: {
'/agent': {
target: 'http://www.liulongbin.top:3006',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/agent/, '')
},
}
}
})
组件:
<template>
<button @click="getbooks">获取书籍信息</button>
</template>
<script setup>
// 导入Store
import { useStore } from "../pinia/store.js";
// 导入API请求
import { getBooks } from "../request/api.js";
const localStore = useStore();
async function getbooks() {
let result = await getBooks();
console.log("result:", result);
}
</script>
结果控制台报错还是和跨域相关:
Access to XMLHttpRequest at 'http://www.liulongbin.top:300...' from origin 'http://localhost:3000' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
'http://www.liulongbin.top:300...'请求这个地址看起来是代理没生效
原因找到了,还是axios封装那里的问题,vite环境下无法使用process。所以在封装axios那里判断环境变量需要写对了。环境配置文件两个.env.development和.env.production。
以开发环境举个栗子:
后面在axios封装中判断环境变量的方法就是: