vite.config.ts
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import path from 'node:path'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue(), vueJsx()],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
},
server: {
cors: true,
proxy: {
"/api": {
target: "http://localhost:8088",
secure: false,
changeOrigin: true, //this one is declare for cross
rewrite: (path) => {console.log(path); return path.replace(/^\/api/, '')}
}
}
}
})
axios.js的配置
import axios from "axios";
let config = {
baseURL: '/api',
timeout: 1000,
withCredentials: true
}
const instance = axios.create(config)
export default instance
页面请求的代码:
$axios.post(‘/user/login’, {
u_account: ruleForm.account,
u_password: ruleForm.password
}).then((response) => {
if (response.data.code === 200) {
let token = response.data.token
console.log('success!')
window.localStorage.setItem('token', token)
} else {
console.log('failed');
}
}).catch((err) => {
console.log(err.message)
})
然后发现vite的proxy是没有触发到的,一直都是调用的vue 的地址,提示“xhr.js:247 POST http://localhost:5173/api/user/login 404 (Not Found)
”;请问大家这个该如何解决跨域的问题。
跨域问题,最好是服务端解决