Detailed explanation of dynamic Axios configuration steps and axios steps

Source: Internet
Author: User
Tags sessionstorage

Detailed explanation of dynamic Axios configuration steps and axios steps

Preface

Previously, Vue-resource was used as the project ajax library when I was writing a vue project. One day in July, especially the updates on Weibo showed that the ajax library should be generic, the technical support for vue-resource is abandoned, and axios is recommended.

We recommend that you use the Vue-cli tool to create and manage projects. Even if you are not familiar with it at the beginning, you can use it to understand its mysteries. The Data Request plug-in officially recommended some time ago is still Vue-resource, but now it has changed to Axios, so you don't have to know why it has changed. It is better to use it anyway, here are some experiences in encapsulating axios requests. What's wrong? I hope you can give me more advice!

The method is as follows:

1. Create a file. After the Vue project is initialized, create another util tool folder under the src directory, which is generally used to store encapsulated function methods, now let's create an http. js file, which encapsulates the axios method.

2. Go directly to the Code (regular version) with detailed comments in the code

Import axios from 'axios '// reference axiosimport {Promise} from 'es6-promise' // introduce Promise // axios to configure axios. defaults. timeout = 5000; // set the timeout value for axios. defaults. baseURL = 'HTTP: // localhost: 4000/api/v1 /'; // This is to call the data interface // http request interceptor (all sent requests must be passed here once). Through this, we can upload the token to the background, sessionStorage is used to store permissions and user information such as tokens. To use cookies, you can encapsulate a function and import it to use axios. interceptors. request. use (config => {const token = sessionStorage. GetItem ("token"); // obtain the token config stored locally. data = JSON. stringify (config. data); config. headers = {'content-type': 'application/json' // sets the cross-origin header. Although many browsers use json to transmit data by default, you must consider IE. }; If (token) {config. headers. authorization = "Token" + token; // carry permission parameter} return config ;}, err =>{ return Promise. reject (err) ;}); // http response Interceptor (all received requests must be passed here once) axios. interceptors. response. use (response => {// response. status = 401 indicates the status code returned when I lost the permissions agreed with the backend or the permissions are insufficient. This can be done by myself and the backend, and it is also possible to return a custom field if (response. status = 401) {router. push ({// push is followed by a parameter object, which can carry many parameters. You can view them on vue-router. For example, the query field indicates the parameter path: '/login'})} return response;}, error => {return Promise. reject (error. response. data)}); export default axios;/*** fetch Request Method * @ param url * @ param params * @ returns {Promise} */export function fetch (url, params ={}) {return new Promise (resolve, reject) =>{ axios. get (url, {params: params }). then (response => {resolve (response. data );}). catch (err =>{ reject (err )})})} /*** post Request Method * @ param url * @ param data * @ returns {Promise} */export function post (url, data = {}) {return new Promise (resolve, reject) => {axios. post (url, data ). then (response => {resolve (response. data) ;}, err =>{ reject (err );})})} /*** patch method encapsulation * @ param url * @ param data * @ returns {Promise} */export function patch (url, data = {}) {return new Promise (resolve, reject) => {axios. patch (url, data ). then (response => {resolve (response. data) ;}, err =>{ reject (err );})})} /*** put method encapsulate * @ param url * @ param data * @ returns {Promise} */export function put (url, data = {}) {return new Promise (resolve, reject) => {axios. put (url, data ). then (response => {resolve (response. data) ;}, err =>{ reject (err );})})}

III. (Dynamic version) axios interceptor is not necessary, not required for every project, and there are more than one Content-Type and Authorization types in headers, in this case, another method is required.

Util/http. js

Import axios from 'axios '// reference axiosimport {Promise} from 'es6-promise' // introduce Promise // The axios configuration and interceptor are no longer needed, here I use a dynamic configuration of the data request address, in the App. in vue, the code is below, and this is not necessary. // Set a default header under cmd_^. You can overwrite the data when using it. For example, if the fetch (GET) method is used, no data is requested, but the request header changes, it should be written as fetch ("Address", {},{ "header content here "}) remember that no data is occupied by a Null Object/*** fetch Request Method * @ param url * @ param params * @ returns {Promise} */export function fetch (url, params = {}, headers = {'content-type': 'application/json', // set the cross-origin Header "Authorization": 'jwt '+ sessionStorage. getItem ("authToken")}) {return new Promise (resolve, reject) => {axios. get (url, {params: params, headers: headers }). then (response => {resolve (response. data );}). catch (err => {reject (err. response)}/*** post Request Method * @ param url * @ param data * @ returns {Promise} */export function post (url, data ={}, config = {"headers": {'content-type': 'application/json', // set the cross-origin Header "Authorization": 'jwt '+ sessionStorage. getItem ("authToken") }}) {return new Promise (resolve, reject) => {axios. post (url, data, config ). then (response => {resolve (response. data) ;}, err =>{ reject (err. response) ;})}/*** patch method encapsulate * @ param url * @ param data * @ returns {Promise} */export function patch (url, data ={}, config = {"headers": {'content-type': 'application/json', // set the cross-origin Header "Authorization": 'jwt '+ sessionStorage. getItem ("authToken") }}) {return new Promise (resolve, reject) => {axios. patch (url, data, config ). then (response => {resolve (response. data) ;}, err =>{ reject (err. response) ;})}/*** put method encapsulate * @ param url * @ param data * @ returns {Promise} */export function put (url, data ={}, config = {"headers": {'content-type': 'application/json', // set the cross-origin Header "Authorization": 'jwt '+ sessionStorage. getItem ("authToken") }}) {return new Promise (resolve, reject) => {axios. put (url, data, config ). then (response => {resolve (response. data) ;}, err =>{ reject (err. response );})})}

App. vue (this is the program entry file under the src directory)

<Template> <div id = "app"> <router-view/> </div> </template> <script> import axios from 'axios '; let protocol = window. location. protocol; // protocol let host = window. location. host; // host let reg =/^ localhost +/; if (reg. test (host) {// if you use axios for local project debugging. defaults. baseURL = 'HTTP: // 10.0.xx.xxx: xxxx/api/';} else {// Dynamic Request address axios. defaults. baseURL = protocol + "//" + host + "/api/";} axios. defaults. timeout = 30000; export Default {name: 'app', axios // remember to export here. If the request address is permanently fixed, configure a baserURL according to the 'regular version'.} </script> <style lang = "scss"> // here I am using scss @ import '~ @/Style/style' </style>

Summary

FAQs

Why is dynamic when dynamic is used, because the access address and request address are the same address port number, for example, I access the project through the http://www.cmgos.com (default port 80, then, my baseURL will automatically change to http: www.cmgos.com: 80/api/. The reason for this is that when a project is migrated or http is changed to https one day, you do not need to change the request address, the program is automatically completed.
Is the data request address configured incorrectly? If baseURL is configured, you only need to input the baseURL-based request address when using the encapsulated function. For example, if you input login/, the request address will automatically change to http: www.cmgos.com: 80/api/login/. If not configured, you can directly input the entire request address.

Notes

When using the dynamic version, because no interceptor is used, the following encapsulated functions must be written when an error is returned.err.response.dataTo obtain the returned data, but what I write iserr.responseIn this way, you can get the status code and other information. If you do not need to judge the returned status code, change iterr.response.dataYou can

Well, the above is all the content of this article. I hope the content of this article has some reference and learning value for everyone's learning or work. If you have any questions, please leave a message to us, thank you for your support.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.