赞
踩
参考vite构建的本地开发环境请求第三方接口时如何解决跨域问题-腾讯云开发者社区-腾讯云
报错图片
解决办法:
1. 在vue项目中添加代理,打开vite.config.js,添加代码
-
- // https://vitejs.dev/config/
- export default defineConfig({
- plugins: [
- vue(),
- AutoImport({
- resolvers: [ElementPlusResolver()]
- }),
- Components({
- resolvers: [ElementPlusResolver()]
- })
- ],
- resolve: {
- alias: {
- '@': fileURLToPath(new URL('./src', import.meta.url))
- }
- },
- // 设置代理,解决跨域问题
- server: {
- https: false,
- // 是否自动在浏览器打开
- open: true,
- cors: true,
- proxy: {
- '/path': {
- target: 'http://localhost:8080', // 接口域名,接口服务器地止
- changeOrigin: true,
- secure: false,
- rewrite: (path) => path.replace(/^\/path/, '')
- }
- }
- }
- })
2. 发送axios请求时,接口地址要写成 ‘/path’,直接封装
- import router from '@/router'
- import { useUserStore } from '@/stores'
- import axios from 'axios'
- import { ElMessage } from 'element-plus'
-
- // 地址替换成 /path
- const baseURL = '/path'
- const instance = axios.create({
- timeout: 5000,
- baseURL: baseURL
- })
-
- instance.interceptors.request.use(
- (config) => {
- // 在发送请求之前做些什么
- const userStore = useUserStore()
- if (userStore.token) {
- // console.log(config, userStore.token)
- config.headers.Authorization = userStore.token
- }
- return config
- },
- (error) => {
- // 对请求错误做些什么
- return Promise.reject(error)
- }
- )
-
- // 添加响应拦截器
- instance.interceptors.response.use(
- (response) => {
- // 对响应数据做点什么
-
- if (response.data.code === 0) {
- return response
- }
- ElMessage.warning(response.data.message || '服务异常')
- if (response.state === 401) {
- router.push('/login')
- }
- return Promise.reject(response.data)
- },
- (error) => {
- // 对响应错误做点什么
- ElMessage.error(error.message || '服务异常')
-
- return Promise.reject(error)
- }
- )
-
- export default instance
- export { baseURL }
参考router api 导航守卫 | Vue Router
在路由配置文件中
- import { createRouter, createWebHistory } from 'vue-router'
- import { useUserStore } from '@/stores'
-
- const router = createRouter({
- history: createWebHistory(import.meta.env.BASE_URL),
- routes: [
- {
- path: '/login',
- component: () => import('@/views/login/Login.vue')
- },
- {
- path: '/',
- component: () => import('@/views/layout/LayoutContainer.vue'),
- redirect: '/article/manage',
- children: [
- {
- path: '/article/manage',
- component: () => import('@/views/article/ArticleManage.vue')
- },
- {
- path: '/article/channel',
- component: () => import('@/views/article/ArticleChannel.vue')
- },
- {
- path: '/user/profile',
- component: () => import('@/views/user/UserProfile.vue')
- },
-
- {
- path: '/user/password',
- component: () => import('@/views/user/UserPassword.vue')
- }
- ]
- }
- ]
- })
- // 配置拦截器
- // to:要去的地址, from:来的地址
- router.beforeEach((to) => {
- const userStore = useUserStore()
- if (!userStore.token && to.path !== '/login') {
- return '/login'
- }
- })
-
- export default router
先说结果,再看代码。
下面第一个是代码块是错误的,input中有值也会一直报红校验不过。
第二个代码块是正确的,报错原因是rules对象中属性值名必须和formData中属性值名一样。
- /*
- *错误的代码
- */
- // rules
- const myRules = ref({
- myName:[
- {required:true, message:'必填', trigger:'blur'}
- ]
- })
-
- // formData
- const formData = ref({
- name: null
- })
-
-
- <!-- element-plus -->
- <el-form
- :model="formData"
- :rules="myRules"
- >
- <el-form-item label="姓名" prop="myName">
- <el-input v-model="formData.name" />
- </el-form-item>
- </el-form>
- /**
- *正确的代码
- */
- // rules
- const myRules = ref({
- name:[
- {required:true, message:'必填', trigger:'blur'}
- ]
- })
-
- // formData
- const formData = ref({
- name: null
- })
-
-
- <!-- element-plus -->
- <el-form
- :model="formData"
- :rules="myRules"
- >
- <el-form-item label="姓名" prop="name">
- <el-input v-model="formData.name" />
- </el-form-item>
- </el-form>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。