刚学完配置vue.config.js
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
devServer: {
proxy: {
'/api': {
target: 'http://192.168.1.228:8080', //后端的地址
ws: true,
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
},
}
}
})
发现访问http://localhost:5173/api/login/user访问结果404
经检查package.json文件
"scripts": { "dev": "vite", "build": "vite build", "preview": "vite preview" }
发现Vue 3 在使用 Vite 作为构建工具,所以跨域配置应在
vite.config.js
文件中进行import { fileURLToPath, URL } from 'node:url' import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' // https://vitejs.dev/config/ export default defineConfig({ plugins: [ vue(), ], resolve: { alias: { '@': fileURLToPath(new URL('./src', import.meta.url)) } },server:{ proxy:{ '/api':{ target:'http://192.168.1.228:8080', changeOrigin:true, rewrite:path=>path.replace(/^\/api/,'') } } } })
配置完成重启,访问成功