当前位置: 首页 > article >正文

2024.10月19日- 关于Vue2的 Ajax

使用SpringMVC来简单搭建一个服务器

1. 创建项目SpringServer
2. 配置pom.xml:     spring-webmvc/javax.servlet-api/jackson-databind
3. 配置web.xml:      前端控制器
4. 配置spring-config.xml:    注解驱动、包扫描,视图解析器
5. 创建pojo类型:  User(Integer id,String name,Integer age,String gender)
6. 创建Controller类型:     返回json等各种方法
比如: 
/*http://localhost:8088/SpringServer/cost?name=zhangsan&age=39&gender=f*/
@RequestMapping("/cost")
@ResponseBody
public User handlerData1(User user){
   System.out.println(user);
   return user;
}
7. 测试HTTP请求.....

一、axios简介与入门案例演示

在Vue中,我们可以使用下列方式,来发送ajax请求,但是最近这几年使用的最多的还是axios。

1. xhr:  js原生代码,也就是new XMLHttpRequest(), 我们还得调用其方法,比如xhr.open()   xhr.send()等
2. JQuery:  $.get   $.post  $.ajax  $.load
3. Fetch:   是一个基于Promise的API, 可以发送HTTP请求
4. axios:   是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。

在vue脚手架里,安装axios,安装后,就可以在node_modules里找到axios里

npm install axios

在App.vue里引入axios

<template>
  <div class="container">
    <button @click="sendData">我是一个按钮</button>
  </div>
</template>
<script>
  import axios from 'axios';
  export default {
      name:'App',
      methods: {
          sendData(){
            axios.get('http://localhost:8088/SpringServer/cost',{params:{name:'lisi'}})
            .then(res=>{
                console.log(res.data);
            }).catch(error=>{
                console.log(error);
            })
          }
      }
  }
</script>

查看服务端,传过去了,没有问题

测试发现,报如下错误: 跨域问题。

二、跨域:

是指的是浏览器不能执行其他网站的脚本,从一个域名的网页去请求另一个域名的资源时,域名、端口、协议任一不同,都是跨域。跨域是由浏览器的同源策略造成的,是浏览器施加的安全限制。

2.1 跨域介绍:

指的是浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器对javascript施加的安全限制。

例如:a页面想获取b页面资源,如果a、b页面的协议、域名、端口、子域名不同,所进行的访问行动都是跨域的,而浏览器为了安全问题一般都限制了跨域访问,也就是不允许跨域请求资源。注意:跨域限制访问,其实是浏览器的限制。理解这一点很重要。

2.2 同源策略:

是一种约定,是浏览器的一种安全机制,它阻止了不同域之间进行的数据交互,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响。所谓同源(即指在同一个域)就是两个页面具有相同的协议(protocol),主机(host)和端口号(port)。

简而言之,是指协议,域名,端口都要相同,其中有一个不同都会产生跨域。

2.3 跨域访问示例:

假设有两个网站,A网站部署在:http://localhost:81 即本地ip端口81上;B网站部署在:http://localhost:82 即本地ip端口82上。现在A网站的页面想去访问B网站的信息,A网站页面的代码如下(这里使用jquery的异步请求)。

从错误信息可以看出以上出现了跨域问题。

解决办法:

1. 设置消息头
2. jsonp方法
3. nginx反向代理
4. vue使用:vue-cli配置代理服务器

三、配置代理服务器- 方式一

vue.config.js

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
  lintOnSave: false,
    //开启代理服务器: 配置代理服务器帮你访问的网站域名
  devServer: {
    proxy: 'http://localhost:8088'
  }
})

App.vue

<template>
  <div class="container">
    <button @click="sendGet">发送axios的get请求</button>
  </div>
</template>
<script>
  import axios from 'axios';
  export default {
      name:'App',
      methods: {
          sendGet(){
            axios.get('http://localhost:8080/SpringServer/cost',{params:{name:'lisi'}})
            .then(res=>{
                console.log(res.data);
            }).catch(error=>{
                console.log(error);
            })
          }
      },
  }
</script>

好用,查看浏览器控制台:

解决是解决了,但是有两个不够完美的地方

  • 第一个是,此时只能给一个服务器做代理服务

  • 第二个是,不能灵活的控制是否有代理,比如public文件夹下有个SpringServer/cost文件。那就不走代理了。

四、配置代理服务器- 方式二

vue.config.js

module.exports = {
   pages: {
      index: {
         entry: 'src/main.js',
      },
   },
   lintOnSave:false,
   // 开启代理服务器(方式一)
   // devServer: {
   //     proxy:'http://localhost:5000'
   // }
​
   //开启代理服务器(方式二)
   devServer: {
      proxy: {
         '/wangcongming': { // 匹配所有以指定字符串开头的请求路径
            target: 'http://localhost:8088',  //代理目标服务器的基础路径
            pathRewrite: { '^/wangcongming': '' }
            //ws: true,  // 用于支持websocket。默认就是true
            //changeOrigin: true //用于控制请求头中的host值。true表示使用代理目标服务器的host。默认就是true
         },
         '/zhangfei': {
            target: 'http://localhost:8089',
            pathRewrite: { '^/zhangfei': '' }, //重写路径,替换
            ws: true,
            changeOrigin: true
         }
      }
   }
}

App.vue

<template>
  <div class="container">
    <button @click="handler8088">与8088服务器进行交互</button>
    <button @click="handler8089">与8089服务器进行交互</button>
  </div>
</template>
<script>
  import axios from 'axios';
  export default {
      name:'App',
      methods: {
        handler8088(){
            axios.get('http://localhost:8080/wangcongming/SpringServer/cost',{params:{name:'lisi'}})
            .then(res=>{
                console.log(res.data);
            }).catch(error=>{
                console.log(error);
            })
          },
          handler8089(){
              axios({
                url:"http://localhost:8080/zhangfei/SpringServer2/account",
                method:"post",
                headers:{'content-type':'application/x-www-form-urlencoded'},
                data:{name:'zhangsan',age:32,gender:'f'}
              }).then(function(response){
                  console.log(response.data);
              })
          },
      },
  }
</script>

总结:

  • 优点:可以配置多个代理,且可以灵活的控制请求是否走代理

  • 缺点:配置略微繁琐,请求资源时必须加前缀


http://www.kler.cn/news/365096.html

相关文章:

  • Discuz发布原创AI帖子内容生成:起尔 | AI原创帖子内容生成插件开发定制
  • 雷池社区版有多个防护站点监听在同一个端口上,匹配顺序是怎么样的
  • 面试题:JVM(一)
  • 智能AI监测系统燃气安全改造方案的背景及应用价值
  • vue3使用webSocket
  • GPIO输入和输出
  • C#从零开始学习(面向对象)(3)
  • 【模型学习】
  • 利用Spring Boot实现信息化教学平台
  • 博弈论 C++
  • Python 快速提取PowerPoint文档中的图片
  • 【Vue.js设计与实现】第三篇第9章:渲染器-简单Diff算法-阅读笔记
  • jupyter argparse问题
  • XML解析小坑记录[正则表达式解析]
  • 学习莫烦python---神经网络
  • 重生之“我打数据结构,真的假的?”--3.栈和队列(无习题)
  • PyTorch 介绍
  • Unity Apple Vision Pro 自定义手势识别交互
  • Vuex 状态机
  • Http模块总体设计
  • C# SM2 加签、验签工具
  • 【SpringCloud】Seata微服务事务
  • 【Flutter】路由与导航:基础路由与导航
  • HTML5教程(一)- 网页与开发工具
  • 基于RK3588/算能BM1684 AI盒子:综合视频智能AI分析系统建设方案(三)安全帽、睡岗检测、电瓶车、吸烟场景
  • 51单片机——OLED显示图片