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

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

ztj100 2024-11-02 14:31 21 浏览 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案例

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


相关推荐

30天学会Python编程:16. Python常用标准库使用教程

16.1collections模块16.1.1高级数据结构16.1.2示例...

强烈推荐!Python 这个宝藏库 re 正则匹配

Python的re模块(RegularExpression正则表达式)提供各种正则表达式的匹配操作。...

Python爬虫中正则表达式的用法,只讲如何应用,不讲原理

Python爬虫:正则的用法(非原理)。大家好,这节课给大家讲正则的实际用法,不讲原理,通俗易懂的讲如何用正则抓取内容。·导入re库,这里是需要从html这段字符串中提取出中间的那几个文字。实例一个对...

Python数据分析实战-正则提取文本的URL网址和邮箱(源码和效果)

实现功能:Python数据分析实战-利用正则表达式提取文本中的URL网址和邮箱...

python爬虫教程之爬取当当网 Top 500 本五星好评书籍

我们使用requests和re来写一个爬虫作为一个爱看书的你(说的跟真的似的)怎么能发现好书呢?所以我们爬取当当网的前500本好五星评书籍怎么样?ok接下来就是学习python的正确姿...

深入理解re模块:Python中的正则表达式神器解析

在Python中,"re"是一个强大的模块,用于处理正则表达式(regularexpressions)。正则表达式是一种强大的文本模式匹配工具,用于在字符串中查找、替换或提取特定模式...

如何使用正则表达式和 Python 匹配不以模式开头的字符串

需要在Python中使用正则表达式来匹配不以给定模式开头的字符串吗?如果是这样,你可以使用下面的语法来查找所有的字符串,除了那些不以https开始的字符串。r"^(?!https).*&...

先Mark后用!8分钟读懂 Python 性能优化

从本文总结了Python开发时,遇到的性能优化问题的定位和解决。概述:性能优化的原则——优化需要优化的部分。性能优化的一般步骤:首先,让你的程序跑起来结果一切正常。然后,运行这个结果正常的代码,看看它...

Python“三步”即可爬取,毋庸置疑

声明:本实例仅供学习,切忌遵守robots协议,请不要使用多线程等方式频繁访问网站。#第一步导入模块importreimportrequests#第二步获取你想爬取的网页地址,发送请求,获取网页内...

简单学Python——re库(正则表达式)2(split、findall、和sub)

1、split():分割字符串,返回列表语法:re.split('分隔符','目标字符串')例如:importrere.split(',','...

Lavazza拉瓦萨再度牵手上海大师赛

阅读此文前,麻烦您点击一下“关注”,方便您进行讨论和分享。Lavazza拉瓦萨再度牵手上海大师赛标题:2024上海大师赛:网球与咖啡的浪漫邂逅在2024年的上海劳力士大师赛上,拉瓦萨咖啡再次成为官...

ArkUI-X构建Android平台AAR及使用

本教程主要讲述如何利用ArkUI-XSDK完成AndroidAAR开发,实现基于ArkTS的声明式开发范式在android平台显示。包括:1.跨平台Library工程开发介绍...

Deepseek写歌详细教程(怎样用deepseek写歌功能)

以下为结合DeepSeek及相关工具实现AI写歌的详细教程,涵盖作词、作曲、演唱全流程:一、核心流程三步法1.AI生成歌词-打开DeepSeek(网页/APP/API),使用结构化提示词生成歌词:...

“AI说唱解说影视”走红,“零基础入行”靠谱吗?本报记者实测

“手里翻找冻鱼,精心的布局;老漠却不言语,脸上带笑意……”《狂飙》剧情被写成歌词,再配上“科目三”背景音乐的演唱,这段1分钟30秒的视频受到了无数网友的点赞。最近一段时间随着AI技术的发展,说唱解说影...

AI音乐制作神器揭秘!3款工具让你秒变高手

在音乐创作的领域里,每个人都有一颗想要成为大师的心。但是面对复杂的乐理知识和繁复的制作过程,许多人的热情被一点点消磨。...

取消回复欢迎 发表评论: