Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the method of sending a request in vue

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what is the method of sending request in vue". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what is the method of sending request in vue".

In vue, plug-ins such as vue-resource, axios, and so on are needed to send requests. Axios is a Promise-based HTTP request client used to send requests, which is also officially recommended by vue2.0, while no longer updating and maintaining vue-resource.

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

Vue-- sends http request for detailed explanation

1) vue 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, which is used to send requests, which is also officially recommended by vue2.0. At the same time, vue-resource is no longer updated or maintained.

Send an AJAX request using axios

1. Install axios and introduce

1) npm method: $npm install axios-S or cnpm install axios-S

2) bower method: $bower install axios

3) the way of cdn:

2. How to introduce axios

When installing other plug-ins, you can introduce and Vue.use () directly in main.js, but axios cannot be use, and can only be introduced immediately in each component that needs to send a request

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

First, after the introduction of axios, modify the prototype chain

The second is to combine Vuex to encapsulate an aciton

Option 1: rewrite the prototype chain

First introduce axios into main.js

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

Send a http request in a component

This.$http.post ('/ user', {name: 'xiaoming'}) this.$http ({method:' post',url:'/ user',data: {name: 'xiaoming'}}) / / send get request 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);}); / / send post request this.$http.post ('/ user', {name: 'xiaoming'}) .then (res= > {console.log (res)}) .catch (err= > {console.log (err)})

3. Encapsulate axios for calling

/ * request.js * / / Import axiosimport axios from 'axios'// use element-ui Message to remind import {Message} from' element-ui';//1. Create a new axios instance, const service = axios.create ({/ / Public API-notice here that baseURL:'', / / timeout unit is ms, and the timeout timeout of 3 seconds is set here: 3 * 1000}) / / 2. Request interceptor service.interceptors.request.use (config = > {/ / some processing before sending a request, data conversion, configure request header, set token, set loading, etc., add config.data = JSON.stringify (config.data) as needed) / / data conversion. You can also use qs to transform console.log ('request interceptor', config) config.headers = {'Content-Type':'application/x-www-form-urlencoded' / / configuration request header} / / Note that you need to introduce cookie method or use local localStorage method when using token. It is recommended that js-cookie / / const token = getCookie (' name') / / before taking the token here, you definitely need to get the token and save / / if (token) {/ / config.params = {'token':token} / / if required to carry in the parameters / / config.headers.token= token; / / if required to carry in the request header / /} return config}, error = > {console.log (' error') Promise.reject (error)}) / / 3. Response interceptor service.interceptors.response.use (response = > {/ / some common processing after receiving response data and succeeding, close return response such as loading}, error = > {console.log ('error',error) / * start processing of receiving abnormal response * / if (error & & error.response) {/ / 1. Public error handling / / 2. Deal with switch (error.response.status) {case: error.message = 'error request' break; case 401: error.message = 'unauthorized' according to the response code, please log in again to 'break; case 403: error.message =' deny access' break Case 404: error.message = 'request error, the resource was not found' / / _ window.location.href = "/" break; case 405: error.message = 'request method not allowed' break; case 408: error.message = 'request timeout' break Case 500: error.message = 'server side error' break; case 501: error.message = 'network not implemented' break; case 502: error.message = 'network error' break; case 503: error.message = 'service unavailable' break Case 504: error.message = 'Network timeout' break; case 505: error.message = 'http version does not support this request' break Default: error.message = `connection error ${error.response.status} `} else {/ / timeout processing if (JSON.stringify (error) .timeout ('timeout')) {Message.error (' server response timeout) Please refresh the current page')} Message.error ('failed to connect to the server')} Message.error (error.message) / * end of processing * / / if no error handling is required, the above processing can be omitted from return Promise.resolve (error.response)}) / / 4. Import file export default service/**** http.js * / / Import encapsulated axios instance import request from'. / request'const http = {/ * methods: request * @ param url request address * @ param params request parameter * / 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 export default httpimport http from'. / http'///** * @ parms resquest request address for example: http://197.82.15.15:8088/request/... * @ param'/ testIp' represents config in vue-cil Agent configured in index.js * / let resquest = "" / / get request export function getListAPI (resquest,params) {return http.get (`${resquest} / getList.json`, params)} / / post request export function postFormAPI (resquest,params) {console.log ('send post request') return http.post (` ${resquest} `, params)} / / put request export function putSomeAPI (resquest,params) {return http.put (` ${resquest} / putSome.json`) Params)} / / delete request export function deleteListAPI (resquest,params) {return http.delete (`${resquest} / deleteList.json`, params)}

Resolve Vue cross-domain issues:

Solution: in scaffolding, in index.js under config

Add these properties to the proxyTable object of dev

/ / Paths assetsSubDirectory: 'static', assetsPublicPath:' /', proxyTable: {"/ api": {target: "whether the domain name of the https://xin.yuemei.com/V603/channel/getScreenNew/",// interface changeOrigin:true,// is cross-domain pathRewrite: {" ^ / api ":"/ / the rewrite is empty. At this time, api is equivalent to the base address of the above target interface}.

Then request here to use axios to request

The prefix api is equivalent to the base address when requested.

Axios.post ("/ api") .then (res = > {console.log (res); this.data = res.data.data;}); / / if there is a parameter request axios.post ("/ api?key=111") .then (res = > {console.log (res); this.data = res.data.data;})

Remember to rerun the project after configuration (remember)

There are two ways to send an Ajax request

One: through the XHR object

Request line:

Method:post or get url: request address

Request header:

Host: host addr

Cookie

Content-type: request body content

Request body:

Response line: status

Response heads: multiple response heads

Responders:

Json/ Picture / css/js/html

Two: through the fetch function

Thank you for your reading, the above is the content of "what is the method of sending a request in vue". After the study of this article, I believe you have a deeper understanding of what is the method of sending a request in vue, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report