“This is the fourth day of my participation in the First Challenge 2022. For details: First Challenge 2022”
preface
The network request module is the foundation of the front and back end communication in a project, so let’s use Axios to implement the basic network request module in a Vue project.
Project background
- Vue2
- Vue-axios
- axios
PS: Axios is a library, it is not a third party plug-in for Vue, so it cannot be installed directly using vue.use () like other third party plug-ins. In order to more convenient to use we introduce vue – axios (www.npmjs.com/package/vue)… Vue-axios is a small wrapper that integrates AXIOS into vue.js. You can install AXIos like a plug-in.
The installation
npm install --save axios vue-axios
Copy the code
use
import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)
Copy the code
steps
1. Determine the structure
The js code for creating a service folder in the SRC directory encapsulates the generic network request below
interceptors.service.js
The axios interceptor is used to add what needs to be done before the request is sent and after the data is received.api.service.js
: a common method used to encapsulate different types of requests.
Create a folder for apis under the SRC directory
- Create API files corresponding to different function modules
2. The interceptorinterceptors.service.js
Use a Axios interceptor methods interceptor. Interceptors. Request. Use () before sending request to request made some configuration:
- The token of the incoming user is sent to the back end for identification
- Pass in the language currently selected by the user so that the backend can output the corresponding data based on the current language
- Set the loading animation to issue the request
Of course, you can also do more detailed configuration according to the specific requirements of the project
import axios from "axios"; const interceptor = axios.create(); Interceptor. Interceptors. Request. Use (function (config) {/ / set the headers to the user's token if (localStorage. Id_token) { config.headers.Authorization = "Bearer " + localStorage.id_token; } // Set headers to the language currently in use, for use by the backend. config.headers["Accept-Language"] = i18n.locale; // You can use some loading animations. Loading animations can be used when requested. LoadingInstance = loading. service({lock: true, background:) loadingInstance = loading. service({lock: true, background: "transparent" }); return config; }, function(error) {// Stop loading animation, return error. loadingInstance.close(); return Promise.reject(error); });Copy the code
* (PS: I pass in the current language is vuE-i18N suite, want to know can see my article Vue2 project front-end internationalization processing VuE-i18N + element)
Use a Axios interceptor methods interceptor. Interceptors. The response. The use of judgment and receiving the response of the response of the processing of the operation
- The loading animation is closed and data is returned
- If the request fails, close the loading animation, agree rules with the backend, capture the error code, judge the error code and customize how to deal with the error.
The common error handling is page alert. Common error codes: 400- invalid request, 404- unable to find web page, 403- server access prohibited, etc
Interceptor. Interceptors. Response. Use (/ / successful return data function (response) {/ / closed loading animation loadingInstance. Close (); Return response.data; }, // fetch data, Function (error) {if (error.response.status === 400) {switch (error.response.data.message) { case "Not found user": case "Unauthorized": // do nothing. break; case "Blocked": router.push({ path: "/inactive" }); break; Error ("Oop, something went wrong. Please contact us."); }} the if (error. The response. The status = = = 403) {/ / page output error messages (element - the UI) Message. The error (error. The response. The data. The Message). } if (error.response.status === 404) {// jump to 404 page router.push({name: "404"}); } // Disable loading instance.close (); return Promise.reject(error); });Copy the code
Finally export the module
export default interceptor;
Copy the code
3. Encapsulate the public method APIapi.service.js
Common methods
get(resource, slug = "", params)
: Used to get data;post(resource, params, config)
: Used for data submission (new), form submission and file upload, etcpatch(resource, params, config)
.put(resource, params, slug = "")
: Used to update data (modify);delete(resource, params, config)
: Used to delete data.
import Vue from "vue"; / / the introduction of just configured axios interceptor import axios from "@ / service/interceptors. Service"; import VueAxios from "vue-axios"; Const ApiService = {init(VueAxios, axios) {vue. use(VueAxios, axios); / / set the API baseURL Vue. Axios. Defaults. BaseURL = "https://www.qq.com/api/"; Get (resource, slug = "", params) {return vue.axios. get(' ${resource}/${slug} ', { params }).catch(error => { throw error.response; }); }, post(resource, params, config) { return Vue.axios.post(`${resource}`, params, config).catch(error => { throw error.response; }); }, patch(resource, params, slug = "") { return Vue.axios.patch(`${resource}/${slug}`, params).catch(error => { throw error.response; }); }, put(resource, params, slug = "") { return Vue.axios.put(`${resource}/${slug}`, params).catch(error => { throw error.response; }); }, delete(resource, params, slug = "") { return Vue.axios .delete(`${resource}/${slug}`, { data: params }) .catch(error => { throw error.response; }); }}; export default ApiService;Copy the code
4. Main.js introduces the encapsulated network request module
For normal use, it is necessary to introduce the encapsulated network request module
//main.js
import ApiService from "@/service/api.service";
ApiService.init();
Copy the code
5. Create API method files according to different function modules
For example, for the student function module, create @/apis/students.js, and for the teacher function module, create @/apis/teachers.js.
API. Service network request is introduced and API methods are added
*src/apis/students.js* import ApiService from "@/common/api.service"; export default { getStudents() { return ApiService.query("students"); }}Copy the code
Create a separate API file for each function module and write API methods that belong only to that module. The advantage of this method is that when you see the file name of the API, you can understand which function module the API serves, which is more convenient for you to get started quickly and reduce the cost of communication. If the API of a module needs to be adjusted later, the corresponding API file can be quickly located and easily modified.
6. Use it in components
Introduce the API file corresponding to the function module, and call the API method to communicate with the back end when it needs to interconnect with the back end.
*students.vue*
import StudentsApi from "@/apis/students.js";
export default {
data() {
return {
students: null
};
},
computed: {},
watch: {},
async mounted() {
this.students = await StudentsApi.getStudents();
},
methods: {}
};
</script>
Copy the code
summary
The above is what I used in the project network request module encapsulation all operations, I hope you can bring help Thanks to (· ω ·) Blue.