03 vue之 Axios和跨域问题

一、Axios

1、Axios介绍

Axios 是一个开源的可以用在浏览器端和 NodeJS 的异步通信框架,她的主要作用就是实现 AJAX 异步通信,其功

能特点如下:

  • 从浏览器中创建 XMLHttpRequests
  • 从 node.js 创建 http 请求
  • 支持 Promise API
  • 拦截请求和响应
  • 转换请求数据和响应数据
  • 取消请求
  • 自动转换 JSON 数据
  • 客户端支持防御 XSRF (跨站请求伪造)

GitHub:https://github.com/axios/axios

中文:http://www.axios-js.com/zh-cn/docs/

2、为什么要使用 Axios

由于 Vue.js 是一个 视图层框架 并且作者(尤雨溪)严格准守 SoC (关注度分离原则),所以 Vue.js 并不包含

AJAX 的通信功能,为了解决通信问题,作者单独开发了一个名为 vue-resource 的插件,不过在进入 2.0 版本以

后停止了对该插件的维护并推荐了 Axios 框架

3、Axios的使用

准备:

在vue中使用axios:

http://www.axios-js.com/zh-cn/docs/vue-axios.html

3.1 创建项目

重新构建一个vue项目并测试访问:axios-stydy

image-20210323160909173
3.2在index.html中 引入js
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>axios-stydy</title>
    <!-- Bootstrap -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" rel="stylesheet">

  </head>
  <body>
    <div id="app"></div>
    <!-- built files will be auto injected -->
  </body>
  <!-- jQuery (Bootstrap 的所有 JavaScript 插件都依赖 jQuery,所以必须放在前边) -->
  <script src="https://cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
  <!-- 加载 Bootstrap 的所有 JavaScript 插件。你也可以根据需要只加载单个插件。 -->
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"></script>
</html>
3.3 修改App.vue
<template>
  <div id="app">

    <div style="width:50%" class="container">
      <div>
        <h3>Regist</h3>
        <h5>Email</h5>
        <input type="text" class="form-control" v-model="mail" /><br />
		 {{mail}}

        <h5>Password</h5>
        <input type="password" class="form-control" v-model="password" /><br />
		{{password}}
        <h5>Gender</h5>
        <input type="radio" name="gender" v-model="gender" value="female" /><input type="radio" name="gender" v-model="gender" value="male" /><br />
        <h5>Hobby</h5>
        <input type="checkbox" name="hobby" v-model="hobby" value="music">音乐
        <input type="checkbox" name="hobby" v-model="hobby" value="movie">电影
        <input type="checkbox" name="hobby" v-model="hobby" value="sport">运动
        <br/>
        <button type="button" class="btn btn-success">注册</button>

      </div>
    </div>
  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld'

export default {
  name: 'App',
  data(){
    return{
      mail:'',
      password:'',
      gender:'',
      hobby:''
    }
  }
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
3.4 安装vue axios
npm install --save axios vue-axios
cnpm install
npm run dev
3.5 在main.js中引入

在项目中使用axios模块

import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
 
Vue.use(VueAxios, axios)

访问查看:

image-20210323162911478
3.6 发送Ajax请求

准备一个SSM的项目,写一个Controller

package com.kuang.controller;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class VueController {


    @RequestMapping("register/{mail}/{password}")
    public String register(@PathVariable String mail, @PathVariable String password){
        System.out.println(mail);
        System.out.println(password);
        return "register Success";
    }
}

启动项目访问测试:

image-20210324163346960

GET方式:

@RequestMapping(value = "register2",method = RequestMethod.GET)
public String register2( String mail,  String password){
    System.out.println(mail);
    System.out.println(password);
    return "register Success2";
}

image-20210324163955658

在App.vue中添加按钮:

<button type="button" class="btn btn-success" @click="registBtn">注册</button>

按钮的方法:

GET请求:

注意:get请求的参数一定在url上面

methods:{
  registBtn:function () {
    this.axios({
      method:'get',                /*请求方式*/
      url:'http://localhost:8090/ssmbuild_war_exploded/register2?mail='+this.mail+'&password='+this.password,  /*请求路径*/
      data:{}
    })
      .then(function (response) {
        console.log(response.data)
      });
  }
}

POST请求:

registBtn2:function () {
  this.axios({
    methods: 'post',
    url:'http://localhost:8090/ssmbuild_war_exploded/register',
    data:{
      mail:this.mail,
      password:this.password
    }
  })
}

提交表单,注册

image-20210324164415138

会出现跨域问题

3.7 后端解决跨域问题

当前服务器的访问端口是8080,但当访问8090会出现跨域问题

服务端解决跨域问题

spring-mvc.xml中添加如下代码

<mvc:cors>  
    <mvc:mapping path="/**"
        allowed-origins="*"
        allowed-methods="POST, GET, OPTIONS, DELETE, PUT,PATCH"
        allowed-headers="Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-
With"
        allow-credentials="true" />
</mvc:cors>

再次测试
image-20210324164817914

注册成功

image-20210324164841756

二、跨域问题

1、什么是跨域问题

这是浏览器对JavaScript的一种安全限制,也就是说浏览器的页面内去访问其他服务器上的资源的时候,就会出现跨域。

同源策略明确了什么情况是属于跨域问题。所谓的同源策略,指的是协议、域名、端口完全相同,才是安全的

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值