[Vue3:axios]:实现实现登陆页面前后端请求,并用Vite解决跨域问题
创始人
2024-11-09 19:36:30
0次

文章目录

  • 一:前置依赖
    • 查看依赖
    • 安装 axios:npm install axios
  • 二:配置文件:创建一个用于全局使用的axios实例,并在main.js或main.ts文件中将其配置为全局属性。
    • 根目录mainjs文件引入axios
  • 三:登录页面发送登录请求:发送请求,成功则用localStorge用户id
    • 成功后跳转页面router.push('/page')
  • 四:解决跨域问题:配置Vite服务器的代理功能来实现
    • 出现CORS跨域异常:
    • 解决跨域异常:vite配置代理
    • 查看发送的CURL:
      • http://localhost:5173/api/base/login 代理到 http://localhost:8092/base/login
  • 五:页面效果:
    • 登录成功:
    • 登录失败:

一:前置依赖

查看依赖

根目录下 package.json 文件

“dependencies”: {
“axios”: “^1.7.2”,
“element-plus”: “^2.7.4”,
“vue”: “^3.4.21”,
“vue-router”: “^4.3.2”
},

安装 axios:npm install axios

PS E:\WorkContent\shanghaikaifangdaxue\shujukuyingyong\testFour\sys-instruction> npm install axios  added 9 packages, and audited 94 packages in 5s  15 packages are looking for funding   run `npm fund` for details  found 0 vulnerabilities 

二:配置文件:创建一个用于全局使用的axios实例,并在main.js或main.ts文件中将其配置为全局属性。

根目录mainjs文件引入axios

import { createApp } from 'vue' import './style.css' import App from './App.vue'  import router from './router' //引入router import ElementPlus from 'element-plus' //引入ElementPlus  const app=createApp(App)  app.use(router) //使用router app.use(ElementPlus) //使用ElementPlus  app.mount('#app') 

三:登录页面发送登录请求:发送请求,成功则用localStorge用户id

成功后跳转页面router.push(‘/page’)

 const submitForm = () => {       loginForm.value.validate((valid) => {         if (valid) {           const resp = axios.post("/api/base/login",               {                 username: form.username,                 pwd: form.password               }           ).then(resp => {             debugger               if (resp.data.code == 500) {                 alert(resp.data.message)               }               if (resp.data.code == 200) {                 localStorage.setItem('username', resp.data.data.id)                 router.push('/page')               }           })           // Handle login logic here         } else {           alert('登录失败');         }       });     }; 
    

四:解决跨域问题:配置Vite服务器的代理功能来实现

出现CORS跨域异常:

{     "message": "Request failed with status code 404",     "name": "AxiosError",     "stack": "AxiosError: Request failed with status code 404\n    at settle (http://localhost:5173/node_modules/.vite/deps/axios.js?v=082c756d:1216:12)\n    at XMLHttpRequest.onloadend (http://localhost:5173/node_modules/.vite/deps/axios.js?v=082c756d:1562:7)\n    at Axios.request (http://localhost:5173/node_modules/.vite/deps/axios.js?v=082c756d:2078:41)",     "config": {         "transitional": {             "silentJSONParsing": true,             "forcedJSONParsing": true,             "clarifyTimeoutError": false         },         "adapter": [             "xhr",             "http",             "fetch"         ],         "transformRequest": [             null         ],         "transformResponse": [             null         ],         "timeout": 0,         "xsrfCookieName": "XSRF-TOKEN",         "xsrfHeaderName": "X-XSRF-TOKEN",         "maxContentLength": -1,         "maxBodyLength": -1,         "env": {},         "headers": {             "Accept": "application/json, text/plain, */*",             "Content-Type": "application/json"         },         "method": "post",         "url": "/api/baseStudentCourse/login",         "data": "{\"username\":\"sdafasda\",\"pwd\":\"adsfadfadsfa\"}"     },     "code": "ERR_BAD_REQUEST",     "status": 404 } 

在这里插入图片描述

解决跨域异常:vite配置代理

  1. 打开项目中的vite.config.js文件(如果你使用的是vite.config.ts,则是相同的配置)。

  2. 在配置文件中,添加一个proxy配置项,指定需要代理的API地址以及相应的目标服务器地址

默认配置:

import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue'  // https://vitejs.dev/config/ export default defineConfig({   plugins: [vue()], }) 

变更后配置:

import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue'  // https://vitejs.dev/config/ export default defineConfig({    plugins: [vue()],    // 添加代理配置     server: {     proxy: {       '/api': {         target: 'http://localhost:8092/', // 目标服务器地址         changeOrigin: true, // 是否改变源地址         rewrite: (path) => path.replace(/^\/api/, ''), // 重写路径       }     }   } }) 

查看发送的CURL:

curl 'http://localhost:5173/api/base/login' \   -H 'Accept: application/json, text/plain, */*' \   -H 'Accept-Language: zh-CN,zh;q=0.9' \   -H 'Connection: keep-alive' \   -H 'Content-Type: application/json' \   -H 'Origin: http://localhost:5173' \   -H 'Referer: http://localhost:5173/login' \   -H 'Sec-Fetch-Dest: empty' \   -H 'Sec-Fetch-Mode: cors' \   -H 'Sec-Fetch-Site: same-origin' \   -H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36' \   -H 'sec-ch-ua: "Google Chrome";v="125", "Chromium";v="125", "Not.A/Brand";v="24"' \   -H 'sec-ch-ua-mobile: ?0' \   -H 'sec-ch-ua-platform: "Windows"' \   --data-raw '{"username":"asdfadsf","pwd":"adfadfaf"}' 

在这里插入图片描述

http://localhost:5173/api/base/login 代理到 http://localhost:8092/base/login

五:页面效果:

登录成功:

在这里插入图片描述

在这里插入图片描述

登录失败:

在这里插入图片描述
在这里插入图片描述

相关内容

热门资讯

一分钟揭秘辅助!微乐小程序游戏... 一分钟揭秘辅助!微乐小程序游戏破解器,微乐家乡小程序修改器-一直真的有辅助挂1)微乐小程序游戏破解器...
技术分享开挂!微信小程序微乐辅... 技术分享开挂!微信小程序微乐辅助器,微乐贵阳捉鸡麻将能不能开挂-一贯是真的有辅助工具在进入微信小程序...
科技介绍开挂!微乐小程序家乡自... 科技介绍开挂!微乐小程序家乡自建房辅助app,微乐自建房脚本如何下载-其实是有辅助神器1、超多福利:...
重大通报辅助!微信小程序微乐辅... 重大通报辅助!微信小程序微乐辅助器教程,微乐小程序微乐家乡辅助器-都是真的有辅助插件重大通报辅助!微...
玩家必备教程辅助!微信小程序游... 玩家必备教程辅助!微信小程序游戏破解微乐游戏,微信小程序微乐安徽辅助苹果-确实有辅助脚本1、完成微信...
科技分享开挂!微乐手游辅助脚本... 科技分享开挂!微乐手游辅助脚本平台,微乐小程序辅助器免费-其实有辅助神器一、微乐手游辅助脚本平台可以...
发现玩家辅助!微乐小程序辅助工... 您好,微乐小程序辅助工具这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多...
推荐一款透视挂!微乐小程序家乡... 推荐一款透视挂!微乐小程序家乡自建房辅助app,微乐河南小程序微乐辅助脚本-原来存在有辅助挂微乐小程...
一起来探讨开挂!微乐小程序开挂... 一起来探讨开挂!微乐小程序开挂黑科技,微乐自建房免费黑科技推荐-本来真的是有辅助脚本小薇(辅助器软件...
2024教程辅助!微信小程序微... 2024教程辅助!微信小程序微乐辅助免费,微乐小程序辅助教程-都是是真的有辅助挂1、点击下载安装,微...