百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术分类 > 正文

vue 获取后端数据(vue获取后端数据 存入pinia)

ztj100 2024-11-02 14:31 14 浏览 0 评论

proxy 解决请求出错问题



为什么会出现跨域问题?


浏览器的同源策略

首先给出浏览器“同源策略”的一种经典定义,同源策略限制了来自不同源(相对于当前页面而言)的document或script,对当前document的某些属性进行读取或是设置,举例来说,A网站(www.aaa.com)上有某个脚本,在B网站(www.bbb.com)未曾加载该脚本时,该脚本不能读取或是修改B网站的DOM节点数据。


本地测试解决请求办法


vite


代码演示



vite.config.js


import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  //中转服务器
  server:{
    //通过代理实现跨域 http://localhost:20219
   proxy:{
    '/api':{
      //替换的服务器地址
      target: 'http://localhost:20219',
      //开启代理 允许跨域
      changeOrigin: true,
      //设置重写的路径
      rewrite: (path) => path.replace(/^\/api/, ""),
    }
   }
  }
})


运行结果



Vue CLI


代码演示



vue.config.js


const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  devServer: {
    //通过代理实现跨域
   proxy: {
      '/path':{
        //替换的服务器地址
        target: 'https://localhost/prod-api',
        //开启代理 允许跨域
        changeOrigin: true,
        //设置重写的路径
        pathRewrite:{
          '^/path':''
        }
      }
   }
  }
})


运行结果



fetch


Fetch API 提供了一个获取资源的接口(包括跨域请求)。任何使用过 XMLHttpRequest 所有人都能轻松上手,而且新的 API 提供了更强大和灵活的功能集。


优点:

1. 语法简洁,更加语义化
2. 基于标准 Promise 实现,支持 async/await
3. 同构方便,更加底层,提供的API丰富(request, response, body , headers)

4. 脱离了XHR,是ES规范里新的实现方式复制代码


缺点:

1. fetch只对网络请求报错,对400,500都当做成功的请求,服务器返回 400,500 错误码时并不会 reject。
2. fetch默认不会带cookie,需要添加配置项: credentials: 'include'。
3. fetch不支持abort,不支持超时控制,造成了流量的浪费。
4. fetch没有办法原生监测请求的进度,而XHR可以


代码演示


Post请求


后端接口展示



user.vue


<template>
  <h2>用户页面</h2>
  <button @click="userLogin">登入</button>
</template>
<script>
export default {
  data() {
    return {
      user: {
        userTelephone: 12244332222,
        userPassword: "123456"
      },
    };
  },
  //fetch 原生js 是http数据请求的一种方式
  //fetch 返回promise对象
  methods: {
    userLogin() {
      fetch("api/user/userLoginByPassword", {
        method: "post",
        body: JSON.stringify({
          userPassword: this.user.userPassword,
          userTelephone: this.user.userTelephone
        }),
        headers: {
          "Content-Type": "application/json",
        },
      })
        .then((res) => {
          console.log(res);
          //json()将响应body 解析json的promise
          // console.log(res.json());
          return res.json();
        })
        .then((res) => {
          console.log(res);
        });
    },
  },
};
</script>


运行效果


编辑Get请求


后端接口展示



user.vue


<template>
  <h2>用户页面</h2>
</template>
<script>
export default {
  //fetch 原生js 是http数据请求的一种方式
  //fetch 返回promise对象
  created() {
    //获取验证图片
      fetch("/api/user/toCreateVerifyImg", {
        method: "get"
      })
        .then((res) => {
          console.log(res);
          //json()将响应body 解析json的promise
          // console.log(res.json());
          return res.json();
        })
        .then((res) => {
          console.log(res);
        });
    }
};
</script>


运行结果



Axios

官网:Axios API | Axios 中文文档 | Axios 中文网 (axios-http.cn)


Axios 是一个基于 promise 网络请求库,作用于node.js 和浏览器中。 它是 isomorphic 的(即同一套代码可以运行在浏览器和node.js中)。在服务端它使用原生 node.js http 模块, 而在客户端 (浏览端) 则使用 XMLHttpRequests。


axios优点:

支持node端和浏览器端 支持 Promise 丰富的配置项


安装


使用 npm:


$ npm install axios


查看是否安装成功



代码演示


Post请求


后端接口演示



User.vue


<template>
  <h2>用户页面</h2>
  <button @click="userLogin">登入</button>
</template>
<script>
import axios from 'axios'
export default {
  data() {
    return {
      user: {
        userTelephone: 12244332222,
        userPassword: "123456",
      },
    };
  },
  methods: {
    //登入
    userLogin() {
      axios
        .post("api/user/userLoginByPassword", {
          userPassword: this.user.userPassword,
          userTelephone: this.user.userTelephone,
        })
        .then(function (response) {
          console.log(response);
        })
        .catch(function (error) {
          console.log(error);
        });
    },
  },
};
</script>


运行结果



Get请求


后端接口演示



User.vue


<template>
  <h2>用户页面</h2>
</template>
<script>
import axios from "axios";
export default {
  created() {
    //获取验证图片
    axios
      .get("api/user/toCreateVerifyImg")
      .then(function (response) {
        console.log(response);
      })
      .catch(function (error) {
        console.log(error);
      })
      .then(function () {
        // 总是会执行
        console.log("总是会执行");
      });
  },
};
</script>


运行结果



TS 封装Axios



代码演示


request index.ts


import axios from "axios";
//创建axios实例
const service=axios.create({
    //url开头
    baseURL:"path",
    timeout: 5000,
    //请求头配置
    headers:{
        "Content-Type": "application/json; charset=utf-8"
    }
})
//请求拦截
service.interceptors.request.use((config)=>{
    //请求头放token
    config.headers=config.headers || {}
    if(localStorage.getItem('token')){
        config.headers.Authorization=localStorage.getItem('token') || ""
    }
    return config;
})
//响应拦截 
service.interceptors.response.use((res)=>{
    const code:number=res.data.code
    // 如果响应code不为200拦截掉
    if(code!=200){
        return Promise.reject(res.data)
    }
    return res.data;
},(err)=>{
    // 打印错误请求
    console.log(err);
})
export default service


request api.ts


import service from ".";
//登入接口
interface LoginData{
    userTelephone:string,
    userPassword:string
}
export function login(data:LoginData){
    return service({
        url:"/user/userLoginByPassword",
        method: "post",
        data
    })
}


LoginView.vue 部分使用代码 想看=>完整版(登入功能实现)


 //调用登入接口
      login(data.ruleForm).then((res) => {
        console.log(res)
        localStorage.setItem("token", res.data.token);
        router.push("/");
      });

demo案例

  • 感兴趣的可以了解了解(附源码)


相关推荐

使用 Pinia ORM 管理 Vue 中的状态

转载说明:原创不易,未经授权,谢绝任何形式的转载状态管理是构建任何Web应用程序的重要组成部分。虽然Vue提供了管理简单状态的技术,但随着应用程序复杂性的增加,处理状态可能变得更具挑战性。这就是为什么...

Vue3开发企业级音乐Web App 明星讲师带你学习大厂高质量代码

Vue3开发企业级音乐WebApp明星讲师带你学习大厂高质量代码下栽课》jzit.top/392/...

一篇文章说清 webpack、vite、vue-cli、create-vue 的区别

webpack、vite、vue-cli、create-vue这些都是什么?看着有点晕,不要怕,我们一起来分辨一下。...

超赞 vue2/3 可视化打印设计VuePluginPrint

今天来给大家推荐一款非常不错的Vue可拖拽打印设计器Hiprint。引入使用//main.js中引入安装import{hiPrintPlugin}from'vue-plugin-...

搭建Trae+Vue3的AI开发环境(vue3 ts开发)

从2024年2025年,不断的有各种AI工具会在自媒体中火起来,号称各种效率王炸,而在AI是否会替代打工人的话题中,程序员又首当其冲。...

如何在现有的Vue项目中嵌入 Blazor项目?

...

Vue中mixin怎么理解?(vue的mixins有什么用)

作者:qdmryt转发链接:https://mp.weixin.qq.com/s/JHF3oIGSTnRegpvE6GSZhg前言...

Vue脚手架安装,初始化项目,打包并用Tomcat和Nginx部署

1.创建Vue脚手架#1.在本地文件目录创建my-first-vue文件夹,安装vue-cli脚手架:npminstall-gvue-cli安装过程如下图所示:创建my-first-vue...

新手如何搭建个人网站(小白如何搭建个人网站)

ElementUl是饿了么前端团队推出的桌面端UI框架,具有是简洁、直观、强悍和低学习成本等优势,非常适合初学者使用。因此,本次项目使用ElementUI框架来完成个人博客的主体开发,欢迎大家讨论...

零基础入门vue开发(vue快速入门与实战开发)

上面一节我们已经成功的安装了nodejs,并且配置了npm的全局环境变量,那么这一节我们就来正式的安装vue-cli,然后在webstorm开发者工具里运行我们的vue项目。这一节有两种创建vue项目...

.net core集成vue(.net core集成vue3)

react、angular、vue你更熟悉哪个?下边这个是vue的。要求需要你的计算机安装有o.netcore2.0以上版本onode、webpack、vue-cli、vue(npm...

使用 Vue 脚手架,为什么要学 webpack?(一)

先问大家一个很简单的问题:vueinitwebpackprjectName与vuecreateprojectName有什么区别呢?它们是Vue-cli2和Vue-cli3创建...

vue 构建和部署(vue项目部署服务器)

普通的搭建方式(安装指令)安装Node.js检查node是否已安装,终端输入node-v会使用命令行(安装)npminstallvue-cli-首先安装vue-clivueinitwe...

Vue.js 环境配置(vue的环境搭建)

说明:node.js和vue.js的关系:Node.js是一个基于ChromeV8引擎的JavaScript运行时环境;类比:Java的jvm(虚拟机)...

vue项目完整搭建步骤(vuecli项目搭建)

简介为了让一些不太清楚搭建前端项目的小白,更快上手。今天我将一步一步带领你们进行前端项目的搭建。前端开发中需要用到框架,那vue作为三大框架主流之一,在工作中很常用。所以就以vue为例。...

取消回复欢迎 发表评论: