[Vue3:axios]:实现实现登陆页面前后端请求,并用Vite解决跨域问题

文章目录

一:前置依赖

查看依赖

根目录下 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

cpp 复制代码
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

vbnet 复制代码
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')

vbnet 复制代码
 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('登录失败');
        }
      });
    };
objectivec 复制代码
<template>
  <div>
    <el-form ref="loginForm" :model="form" :rules="rules">
      <div class="title-container" style="margin-top: 20px;">
        <h3 class="title">学生管理平台</h3>
      </div>
      <el-form-item prop="username">
        <el-input v-model="form.username" placeholder="Username"></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input type="password" v-model="form.password" placeholder="Password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="submitForm">Login</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import axios from "axios";

export default {
  name: 'Login',
  setup() {
    const loginForm = ref(null);
    const form = reactive({
      username: '',
      password: ''
    });
    const rules = {
      username: [
        { required: true, message: 'Please input username', trigger: 'blur' }
      ],
      password: [
        // { required: true, message: 'Please input password', trigger: 'blur' },
        // { min: 6, message: 'Password length should be greater than 6', trigger: 'blur' }
      ]
    };
    const router = useRouter();
    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('登录失败');
        }
      });
    };
    return {
      loginForm,
      form,
      rules,
      submitForm
    };
  }
};
</script>

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

出现CORS跨域异常:

yaml 复制代码
{
    "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地址以及相应的目标服务器地址

默认配置:

swift 复制代码
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
})

变更后配置:

yaml 复制代码
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:

yaml 复制代码
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

五:页面效果:

登录成功:

登录失败:


相关推荐
落魄实习生11 小时前
AI应用-本地模型实现AI生成PPT(简易版)
python·ai·vue·ppt
bpmf_fff13 小时前
二九(vue2-05)、父子通信v-model、sync、ref、¥nextTick、自定义指令、具名插槽、作用域插槽、综合案例 - 商品列表
vue
java_heartLake19 小时前
Vue3之状态管理Vuex
vue·vuex·前端状态管理
小马超会养兔子20 小时前
如何写一个数字老虎机滚轮
开发语言·前端·javascript·vue
小阳生煎1 天前
多个Echart遍历生成 / 词图云
vue
小马超会养兔子2 天前
如何写一个转盘
开发语言·前端·vue
bpmf_fff2 天前
二八(vue2-04)、scoped、data函数、父子通信、props校验、非父子通信(EventBus、provide&inject)、v-model进阶
vue
好开心333 天前
04、Vue与Ajax
前端·ajax·前端框架·vue·js
工业互联网专业3 天前
Python毕业设计选题:基于Python的社区爱心养老管理系统设计与实现_django
python·django·vue·毕业设计·源码·课程设计
平行线也会相交3 天前
云图库平台(一)后端项目初始化
spring boot·vue·云图库平台