美文网首页vue技术栈
Vue Axios跨域、文件上传

Vue Axios跨域、文件上传

作者: 独自迈向前方 | 来源:发表于2018-02-27 18:04 被阅读2173次

本文以vue-cli中使用axios为例

安装

npm install --save axios

引用(注册到VUE实例中)

import Vue from 'vue'
import Axios from 'axios'

//querystring 为nodejs 内置模块 在post 请求中使用到 写在这里是防止不小心将import 语句写在代码区块内的伙伴
//作用 将 类似 {a:'aa',b:'bb'} 与 a=aa&b=bb 类型的互相转换编码
import querystring from 'querystring' // 或者 import qs from 'qs'
Vue.prototype.$querystring=qs

//create([options]) 方法允许设置一些默认的配置 (可选) 如下:
const axios=Axios.create({
    baseURL:'http://127.0.0.1/', // 通常配置基础的接口入口地址 
    timeout:5000, // 请求超时时间
    headers:{// 这里可设置所有的请求头
        'Content-Type':'application/x-www-form-urlencoded', //该项建议设置 如果未 POST请求时 数据未做处理时会出现错误,最理想的解决方法就是 直接设置该项
    },
    withCredentials:true,//是否允许发送Cookie 如果为true 则服务器的 Access-control-Allow-Credentials 必须为 true 来源为 XMLHttpRequest的withCredentials配置项

    // 以下两项为拦截器配置 可最后再看
    transformRequest: [function (data) {//准备发送请求触发的事件 类型:Array || Function 可以是一个函数或数组 data 为发送的数据 get 为undefined
        console.log('准备发送请求:',data)
        // 此处可对发送的数据进行处理      
        return data; //最终数据
    }],
    transformResponse: [function (data) {//接收到数据首先处理的函数 ,data 为服务器返回的数据(// 1.响应结构 里的  rs.data)
        console.log('接收到数据:',data)
        return data;//最终数据 
    },function (data) {//当为数组时 窜行操作  data 为上一步中的最终数据
        console.log('before',data)
        return data;
    }],
})
axios.all=Axios.all; // 由于使用create方法返回的 实例缺少了 all 方法 在这里 加进去 all() 方法主要用于并发请求 , 在文章末尾讲解
Vue.prototype.$http=axios; // 绑定到 Vue 实例中 如果不进行create()配置可直接:Vue.prototype.$http=Axios;
// 注:后续使用 只需 const axios=this.$http; 即可.

  • 注:withCredentials:true 项开启可实现服务器与前端互通cookie、session
  • 更多配置请参考 Axios中文说明

跨域请求服务器配置(此处以php为例 ,简单说就是设置服务器 headers)

header('Access-Control-Allow-Origin:*'); // 远程访问权限允许所有(该项必须设置)
//注:如果 Access-control-Allow-Credentials 为 true 则 Access-Control-Allow-Origin 必须 设置确定的域名 不能使用通配符。如下:
header('Access-Control-Allow-Origin:http://127.0.0.1:8080');

header('Access-control-Allow-Credentials:true');//默认 false  是否同意发送Cookie  如果前端请求 withCredentials:true 则该项须设置为true

header('Access-control-Allow-Methods:GET,POST');//可选 远程请求方法控制 (get post put delete ......)


  • 注:Access-control-Allow-Credentials:true 项开启可实现服务器与前端互通cookie、session

GET 请求

axios.get(url,[configs])

  • url:请求的接口地址 如果为相对路径则 会在 url 前加上 配置项中的 baseURL 型如:baseURL+url
  • configs 临时的配置项 仅对当次请求有效 (可选)
// 如下 可针对不同的请求进行特例配置设置 
this.$http.get('/api.php',{
  //baseURL:'http://127.0.0.1/axios/',
  //timeout:10000,
})
.then(rs=>{// axios 实现了 Promise 接口 then 方法即是我们的请求成功回调 传入的参数 rs 为返回数据 (1.响应结构)
  console.log(rs)
})
.catch(err=>{// Promise 接口 catch 方法 为错误处理回调 err 为错误信息
  console.log(err)
})

// 1.响应结构:
{
  data:Array, //我们从返回的数据 
  status:200, //服务器状态码
  statusText:'ok', //服务器相应码信息
  config:Object, //当次请求的axios配置信息
  headers:Object, //服务响应头
  request:XMLHttpRequest // xhr 对象
}

POST 请求

axios.post(url,data,[configs])

  • url:请求的接口地址 如果为相对路径则 会在 url 前加上 配置项中的 baseURL 型如:baseURL+url
  • data POST数据 (Object、String、FormData、URLSearchParams 、ArrayBuffer ......)
  • configs 临时的配置项 仅对当次请求有效 (可选)
let data={
  title:'POST传输',
  content:'通常以一个对象直接发送,服务器所收到的数据并不是期望的那样!',
}
// post 请求如果data 为空请传 {} 省略将出现错误警告
// 我们在开头说到 querystring 模块在此处使用的问题 。以下`#`号内的代码如果不写 那么服务器接收到的数据是会有很大差别的。 可先自行试验。
// 当然大部分人都说使用 URLSearchParams 或者 FormData进行处理,但我觉得有点啰嗦。

// ###################这是井号#####################
  data=this.$querystring.stringify(data)
// ###################这是井号#####################

this.$http.post('/api.php',data)
.then(rs=>{
  console.log(rs)
})

POST+FormData 实现跨域异步上传

单文件上传 例:
<template>
  <div>
    <input type="file" @change="uploads">  
    <p></p>
    <img :src="imgUrl">
  </div>
</template>
<script>
export default {
  data(){
    return {
      imgUrl:'',
    }
  },
  methods:{
    uploads(e){
      const file=e.target.files[0];//获取到当前文件对象

      let URL=window.URL||window.webkitURL; // 与上传没有关系(可选)
      this.imgUrl=URL.createObjectURL(file); // 这是为了显示图片而已, 与上传没有关系(可选)

      // 传递一个 FormData 对象 即可 
      let formData=new FormData();
      formData.append('file',file); // 'file' 可变 相当于 input 表单的name 属性
      // 服务器只需按照正常的上传程序代码即可
      this.$http.post('/upload.php',formData).then(rs=>{
         console.log(rs.data)
      }).catch(err=>{
         console.log(err)
      })
    },
  }
}
</script>

多文件上传 例:
<template>
  <div>
    <input type="file" @change="uploads">  
    <button @click="uploadAll">uploadAll</button>
    <p></p>
    <img :src="item" v-for="item of images" style="widtn:100px;height:100px;margin:10px;">
  </div>
</template>

<script>
export default {
  data(){
    return {
      images:[],//显示图片所用 与上传没有关系(可选)
      formData:new FormData(),//在此处初始化时,即实例化 FormData
    }
  },
  methods:{
    uploads(e){
      const file=e.target.files[0];

      let URL=window.URL||window.webkitURL;// 与上传没有关系(可选)
      this.images.push(URL.createObjectURL(file)) // 这是为了显示图片而已, 与上传没有关系(可选)

      this.formData.append('file[]',file); // 'file[]' 代表数组 其中`file`是可变的
    },
    uploadAll(){
      //当点击上传时直接上传  服务器按照正常的多文件上传操作即可
      this.$http.post('/a.php',this.formData).then(rs=>{
        console.log(rs.data)
      }).catch(err=>{
        console.log(err)
      })
    }
  }
}
</script>

并发请求



// 首先需要并发的声明操作方法a()、b()如下
function a() {
  return this.$http.get('/a.php');
}
function b() {
  let data={
    val:"来自http://127.1.0.1:8080的POST请求",
  }
  return this.$http.post('/b.php',this.$querystring.stringify(data));
}

// all()方法接收一个数组  数组的项目 即为 并发方法 
this.$http.all([a(),b()]) 
.then(rs=>{
  // rs 为一个数组  每一项对应 all 方法中 对应的并发方法 的返回值
  console.log(rs)
})

相关文章

网友评论

本文标题:Vue Axios跨域、文件上传

本文链接:https://www.haomeiwen.com/subject/emkmxftx.html