PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

vue中用什么来发送请求

青灯夜游
青灯夜游 原创
2022-01-10 14:52:00 6236浏览

在vue中,需要使用vue-resource、axios等插件来发送请求。axios是一个基于promise的http请求客户端,用来发送请求,也是vue2.0官方推荐的,同时不再对vue-resource进行更新和维护。

本教程操作环境:windows7系统、vue2.9.6版,DELL G3电脑。

Vue——发送http请求详解

1)vue本身不支持发送AJAX请求,需要使用vue-resource、axios等插件实现。

2) axios是一个基于Promise的HTTP请求客户端,用来发送请求,也是vue2.0官方推荐的,同时不再对vue-resource进行更新和维护。

使用axios发送AJAX请求

1、安装axios并引入

1)npm的方式: $ npm install axios -S  或 cnpm install axios -S

2)bower的方式:$ bower install axios

3)cdn的方式:

2、如何引入使用axios

安装其他插件的时候,可以直接在 main.js 中引入并 Vue.use(),但是 axios 并不能 use,只能每个需要发送请求的组件中即时引入

为了解决这个问题,有两种开发思路,

一是在引入 axios 之后,修改原型链

二是结合 Vuex,封装一个 aciton

方案一:改写原型链

首先在 main.js 中引入 axios

import axios from 'axios'
Vue.prototype.$http= axios

在组件中发送http请求

this.$http.post('/user',{name: 'xiaoming'})
this.$http({method: 'post',url: '/user',data: {name: 'xiaoming'}})

//发送get请求
this.$http.get('/user?ID=12345')
 .then(res=> { console.log(response); }) 
.catch(err=> { console.log(error); });
this.$http.get('/user',{params:{ID:12345}}) 
.then(res=> { console.log(response); }) 
.catch(err=> { console.log(error); });

//发送post请求

this.$http.post('/user',
{name: 'xiaoming'}
) 
.then(res=> { console.log(res) }) 
.catch(err=> { console.log(err)});

 3、封装axios进行调用

/****   request.js   ****/
// 导入axios
import axios from 'axios'
// 使用element-ui Message做消息提醒
import { Message} from 'element-ui';

//1. 创建新的axios实例,
const service = axios.create({
  // 公共接口--这里注意后面会讲
  baseURL: '',
  // 超时时间 单位是ms,这里设置了3s的超时时间
  timeout: 3 * 1000
})
// 2.请求拦截器
service.interceptors.request.use(config => {

  //发请求前做的一些处理,数据转化,配置请求头,设置token,设置loading等,根据需求去添加
  config.data = JSON.stringify(config.data); //数据转化,也可以使用qs转换
  console.log('请求拦截器中',config)
  config.headers = {
    'Content-Type':'application/x-www-form-urlencoded' //配置请求头
  }
  //注意使用token的时候需要引入cookie方法或者用本地localStorage等方法,推荐js-cookie

  // const token = getCookie('名称');//这里取token之前,你肯定需要先拿到token,存一下

  // if(token){
  //   config.params = {'token':token} //如果要求携带在参数中
  //   config.headers.token= token; //如果要求携带在请求头中
  // }

  return config
}, error => {
  console.log('错误')
  Promise.reject(error)
})

// 3.响应拦截器
service.interceptors.response.use(response => {
  //接收到响应数据并成功后的一些共有的处理,关闭loading等

  return response
}, error => {
  console.log('error',error)
  /***** 接收到异常响应的处理开始 *****/
  if (error && error.response) {
    // 1.公共错误处理
    // 2.根据响应码具体处理
    switch (error.response.status) {
      case 400:
        error.message = '错误请求'
        break;
      case 401:
        error.message = '未授权,请重新登录'
        break;
      case 403:
        error.message = '拒绝访问'
        break;
      case 404:
        error.message = '请求错误,未找到该资源'
        // window.location.href = "/"
        break;
      case 405:
        error.message = '请求方法未允许'
        break;
      case 408:
        error.message = '请求超时'
        break;
      case 500:
        error.message = '服务器端出错'
        break;
      case 501:
        error.message = '网络未实现'
        break;
      case 502:
        error.message = '网络错误'
        break;
      case 503:
        error.message = '服务不可用'
        break;
      case 504:
        error.message = '网络超时'
        break;
      case 505:
        error.message = 'http版本不支持该请求'
        break;
      default:
        error.message = `连接错误${error.response.status}`
    }
  } else {
    // 超时处理
    if (JSON.stringify(error).includes('timeout')) {
      Message.error('服务器响应超时,请刷新当前页')
    }
    Message.error('连接服务器失败')
  }
  Message.error(error.message)
  /***** 处理结束 *****/
  //如果不需要错误处理,以上的处理过程都可省略
  return Promise.resolve(error.response)
})
//4.导入文件
export default service
/****   http.js   ****/
// 导入封装好的axios实例
import request from './request'


const http ={
  /**
   * methods: 请求
   * @param url 请求地址
   * @param params 请求参数
   */
  get(url,params){
    const config = {
      method: 'get',
      url:url
    }
    if(params) config.params = params
    return request(config)
  },
  post(url,params){
    console.log(url,params)
    const config = {
      method: 'post',
      url:url
    }
    if(params) config.data = params
    return request(config)
  },
  put(url,params){
    const config = {
      method: 'put',
      url:url
    }
    if(params) config.params = params
    return request(config)
  },
  delete(url,params){
    const config = {
      method: 'delete',
      url:url
    }
    if(params) config.params = params
    return request(config)
  }
}
//导出
export default http
import http from './http'
//
/**
 *  @parms resquest 请求地址 例如:http://197.82.15.15:8088/request/...
 *  @param '/testIp'代表vue-cil中config,index.js中配置的代理
 */
// let resquest = ""

// get请求
export function getListAPI(resquest,params){
  return http.get(`${resquest}/getList.json`,params)
}
// post请求
export function postFormAPI(resquest,params){
  console.log('发送post请求')
  return http.post(`${resquest}`,params)
}
// put 请求
export function putSomeAPI(resquest,params){
  return http.put(`${resquest}/putSome.json`,params)
}
// delete 请求
export function deleteListAPI(resquest,params){
  return http.delete(`${resquest}/deleteList.json`,params)
}

 解决Vue跨域问题:

解决方法:在脚手架中的config下的index.js中

在 dev 的 proxyTable 对象中添加这些属性

// Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      "/api":{
        target:"https://xin.yuemei.com/V603/channel/getScreenNew/",//接口域名
        changeOrigin:true,//是否跨域
        pathRewrite:{
          "^/api":""//重写为空,这个时候api就相当于上面target接口基准地址
        }
      }
    },

然后请求这里用axios请求
请求的时候前缀api就相当于基准地址了

axios.post("/api").then(res => {
      console.log(res);
      this.data = res.data.data;
 });
 //如果有参数请求
 axios.post("/api?key=111").then(res => {
      console.log(res);
      this.data = res.data.data;
 });

配置完记得重跑一下项目(切记)

想要发送Ajax请求 通过两种方式 

一:通过XHR对象 

请求行:

method:post 或get  url:请求地址

请求头:

host:主机地址

cookie
content-type:请求体内容

请求体:

响应行:status

响应头:多个响应头

响应体:

json/图片/css/js/html

二:通过fetch函数

【相关推荐:vue.js教程

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。