Home  >  Article  >  Web Front-end  >  What to use in vue to send requests

What to use in vue to send requests

青灯夜游
青灯夜游Original
2022-01-10 14:52:006494browse

In vue, you need to use vue-resource, axios and other plug-ins to send requests. axios is a Promise-based HTTP request client used to send requests. It is also officially recommended by vue2.0. At the same time, vue-resource will no longer be updated and maintained.

What to use in vue to send requests

The operating environment of this tutorial: windows7 system, vue2.9.6 version, DELL G3 computer.

Vue - Detailed explanation of sending http requests

1) Vue itself does not support sending AJAX requests and needs to be implemented using plug-ins such as vue-resource and axios.

2) axios is a Promise-based HTTP request client used to send requests. It is also officially recommended by vue2.0. At the same time, vue-resource will no longer be updated and maintained.

Use axios to send AJAX requests

1. Install axios and introduce

1) npm The way: $ npm install axios -S or cnpm install axios -S

2) bower way: $ bower install axios

3) cdn way: f155dea2bfdc6b8a01d87d8f35f18fdc2cacc6d41bbb37262a98f745aa00fbf0

2. How to introduce and use axios

to install other When plugging in, you can directly introduce Vue.use() in main.js, but axios cannot be used. It can only be introduced immediately in each component that needs to send requests.

In order to solve this problem, there are two There are two development ideas,

The first is to modify the prototype chain after introducing axios

The second is to combine Vuex to encapsulate an aciton

Option 1: Rewrite the prototype chain

First introduce axios in main.js

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

Send http request in the component

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. Encapsulate axios to call

/****   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)
}

Solution Vue cross-domain problem:

Solution: In index.js under config in the scaffolding

Add these attributes in the proxyTable object of dev

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

Then request here using axios request
When requesting, the prefix api is equivalent to the base address

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;
 });

Remember to rerun the project after configuring (remember)

You want to send Ajax requests in two ways

One: Through the XHR object

Request line:

method: post or get url: request address

Request header:

host: host address

cookie
content-type: request body content

Request body:

Response line: status

Response header: multiple response headers

Response body:

json/picture /css/js/html

2: Through the fetch function

[Related recommendations: vue.js tutorial]

The above is the detailed content of What to use in vue to send requests. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn