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

How Vue2 uses Axios to initiate requests

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article shows you how Vue2 uses Axios to initiate requests. The content is concise and easy to understand. It will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.

Preface

When you read this article, I hope you already know what cross-domain requests are and how to handle them. I will not repeat them in this article.

The background of this article is based on Springboot2.3, and no business logic will be written in Controller, which is only used to cooperate with front-end debugging.

The R.success used in Controller is a tool class encapsulated by myself, and the code is at the end of the article.

Installation and configuration of Axios

Execute the command to install axios in the project directory

Npm install-S axios

Open the main.js file under the src path, introduce axios dependencies into the file and mount it to the global properties of vue

/ / reference axios depends on import axios from 'axios'// to be hung in vue. Here, mount axios as request, and you can use this.request to call axios in the component. Vue.prototype.request = axios.

The get method in axios is called when initiating the GET request. You can see that this method receives two objects, url and config.

Initiate a simple GET request @ RestController@RequestMapping ("/ user") public class UserController {@ GetMapping ("/ list") public R list () {return R.success ("user list query succeeded!") ;}} query user export default {name: "index", methods: {selectList () {/ / simple GET request only needs to input URL to implement this.request.get ("http://localhost:8000/user/list").then(res = > {console.log (" res ", res)) ) .catch (e = > {console.log ("e", e);})}

Initiate a simple GET request with parameters

@ RestController@RequestMapping ("/ user") public class UserController {@ GetMapping ("/ get") public R get (String id) {return R.success ("user gets success!") ;}} selectOne () {let config = {params: {id: "1"} / / url is followed by the config object, and the params attribute in the config object corresponds to the request parameter this.request.get ("http://localhost:8000/user/get", config). Then (res = > {console.log (" res ", res)) Catch (e = > {console.log ("e", e);})}

Initiate a POST request

The post method in axios is called when initiating the POST request. You can see that the parameter list of this method has three objects.

Initiate a simple POST request @ RestController@RequestMapping ("/ user") public class UserController {@ PostMapping ("/ save") public R save () {return R.success ("user added successfully!") ;} save () {/ / sending a simple POST request is the same as a simple GET request, you only need to change the get method to a post method to this.request.post ("http://localhost:8000/user/save").then(res = > {console.log (" res ", res);}) .catch (e = > {console.log (" e ", e);})}

Initiating a POST request with the parameter (1) @ RestController@RequestMapping ("/ user") public class UserController {/ * generally initiating a POST request is to put the parameter in the body of the request, and then parse through @ RequestBody * here I will not create the entity class Directly use the Map collection to receive * / @ PostMapping ("/ save") public R save (@ RequestBody Map data) {return R.success ("user added successfully!") .setAttribute ("name", data.get ("username")) .setAttribute ("pwd", data.get ("password")) }} save () {let data = {username: "Java pupil,", password: "123456789"} / / you should be able to guess when you see the parameter list You can put the object directly on the second parameter / / it should be noted that the parameter carried by this method is this.request.post ("http://localhost:8000/user/save", data). Then (res = > {console.log (" res ", res)) Catch (e = > {console.log ("e", e);})}

Initiate a POST request with parameters (2)

As mentioned above, the parameters passed directly using data are placed in the request body, and the backend needs to use @ RequestBody to get them. Here, change the parameters to path parameters for submission.

@ RestController@RequestMapping ("/ user") public class UserController {@ PostMapping ("/ save") public R save (String username, String password) {return R.success ("user added successfully!") .setAttribute ("name", username) .setAttribute ("pwd", password) }} save () {let config = {params: {username: "Java pupils," password: "123456789"} / / instead of using data, use config to pass parameters Or encapsulate the object as params to pass this.request.post ("http://localhost:8000/user/save", null, config). Then (res = > {console.log (" res ", res)) Catch (e = > {console.log ("e", e);})}

Upload file test

In addition to GET and POST requests, there are also PUT, DELETE and other requests. Let's not test them one by one to learn about uploading files.

@ RestController@RequestMapping ("/ user") public class UserController {@ PostMapping ("/ upload") public R upload (MultipartFile file, String fileName) {/ / file object is the received file. The processing logic for the file is omitted. Return R.success ("File uploaded successfully!") .setAttribute ("fileName", fileName) } Click to upload export default {name: "index", data () {return {file: null}}, methods: {fileChange (event) {/ / this method will be triggered when a file is selected Store the file object in file this.file = event.target.files [0] }, upload () {/ / create a FormData object, put file in it, or put some other parameters let data = new FormData (); data.append ('file', this.file); data.append (' fileName', "11223344.txt") / / create a config object Set the request header type to multipart/form-data let config = {headers: {'Content-Type':' multipart/form-data'}} / / initiate the request with the object this.request.post ('http://localhost:8000/user/upload', data, config) just created. Then (res = > {console.log ("res") Res) })}

Config configuration of Axios

Through observation, we can find that all requests made by Axios will receive a config object, and the configuration details can be seen in the node_modules/axios/index.d.ts file:

There are many configuration items, I am also a newcomer, many have not been touched, here is a simple test a few others can be checked at any time, recommend an Axios Chinese website

BaseURL

BaseURL is a commonly used attribute. You can set the root address for each request. We only need to pay attention to the request path when initiating the request.

Export default {name: "index", data () {return {config: {baseURL: "http://localhost:8000"}, methods: {test () {let data = {name:" Java pupils, "} This.request.post ("/ user/save", data, this.config) .then (res = > {console.log ("res", res);});},}} timeout

Timeout is also a more commonly used configuration item, which is used to configure the timeout of the request (in millisecond ms). Setting it to 0 means no timeout.

Export default {name: "index", data () {return {config: {baseURL: "http://localhost:8000", timeout: 5000}, methods: {test () {let data = {name:" Zhang Hanzhe "}} This.request.post ("/ user/save", data, this.config) .then (res = > {console.log ("res", res);});},}}

WithCredentials

This attribute is also commonly used. The value of withCredentials is bool, which is used to set whether or not to carry Cookie,Axios requests. By default, Cookie is not allowed. You can print sessionID through Controller for testing.

Export default {name: "index", data () {return {config: {baseURL: "http://localhost:8000", / / requires the server to cooperate with withCredentials: true, timeout: 5000} Methods: {test () {let data = {name: "Java pupils,"} This.request.post ("/ user/save", data, this.config) .then (res = > {console.log ("res", res);});},}}

Axios is here for the time being. Understanding these daily development is basically no problem. After using familiar config, you can try to encapsulate a tool class.

The above is how Vue2 uses Axios to initiate requests. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

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