Table of Contents
Vue - Detailed explanation of sending http requests
Home Web Front-end Front-end Q&A What to use in vue to send requests

What to use in vue to send requests

Jan 10, 2022 pm 02:52 PM
vue send request

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:

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
Copy after login

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)});
Copy after login

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

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接口基准地址
        }
      }
    },
Copy after login

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;
 });
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

How to use watch in vue How to use watch in vue Apr 07, 2025 pm 11:36 PM

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

How to reference js file with vue.js How to reference js file with vue.js Apr 07, 2025 pm 11:27 PM

There are three ways to refer to JS files in Vue.js: directly specify the path using the <script> tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

What does vue multi-page development mean? What does vue multi-page development mean? Apr 07, 2025 pm 11:57 PM

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

How to return to previous page by vue How to return to previous page by vue Apr 07, 2025 pm 11:30 PM

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses <router-link to="/" component window.history.back(), and the method selection depends on the scene.

How to query the version of vue How to query the version of vue Apr 07, 2025 pm 11:24 PM

You can query the Vue version by using Vue Devtools to view the Vue tab in the browser's console. Use npm to run the "npm list -g vue" command. Find the Vue item in the "dependencies" object of the package.json file. For Vue CLI projects, run the "vue --version" command. Check the version information in the <script> tag in the HTML file that refers to the Vue file.

How to use function intercept vue How to use function intercept vue Apr 08, 2025 am 06:51 AM

Function interception in Vue is a technique used to limit the number of times a function is called within a specified time period and prevent performance problems. The implementation method is: import the lodash library: import { debounce } from 'lodash'; Use the debounce function to create an intercept function: const debouncedFunction = debounce(() => { / Logical / }, 500); Call the intercept function, and the control function is called at most once in 500 milliseconds.

See all articles