In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Today, the editor will share with you the relevant knowledge points about how to use axios to send post requests in the vue cli3 project. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look.
Send a post request using axios
React is also applicable.
First, you need to install the corresponding third-party package.
Cnpm I-S axios
Cnpm I-S lodash
And then do the following.
Create a file directory like this in the vue project
Send post request
The contents of the file in index.js are:
Import axios from "axios" import _ from "lodash" / / processing request parameters const coverFormData = (obj) = > {let data = Object.keys (obj.data) .map (item = > {let value = obj.data [item] If (_ .isArray (value) | | _ .isObject (value)) {value = JSON.stringify (value)} return encodeURIComponent (item) +'='+ encodeURIComponent (value);}. Join ('&'); return {data: data, url: obj.url};} function post (obj) {const {data, url} = coverFormData (obj) Return new Promise ((resolve, reject) = > {axios.post (url, data). Then (res = > {/ / obj.success? Obj.success (res): null resolve (res.data);}) .catch (error = > {/ / obj.error? Obj.error (error): null; reject (error);})} let requests = {} requests.post = post export default requests
Use:
Effect:
Send a get request to add the following code to index.js: requests.get = obj = > {const {data, url} = coverFormData (obj); return new Promise ((resolve, reject) = > {axios.get (url +'?'+ data). Then (res = > {obj.success? Obj.success (res): null; resolve (res.data);}) .catch (error = > {obj.error? Obj.error (error): null; reject (error);})})}
Use exactly the same as post, except to change requests.post to request.get
Vue uses axios's trample to record axios cross-domain
In a project I wrote, I wanted to send the student number and password directly to the school's educational administration system, but it turned out to be cross-domain.
Original code
/ / url is the domain name axios.get (`${url}? method=authUser&xh=$ {this.sNo} & pwd=$ {this.password}`) .then ((res) = > {/ /...}) .catch ((err) = > {/ /.})
When looking for solutions to cross-domain problems on the Internet, I see that many of them are modified under config. File, but there is no config folder in the vue3 project created by vue-cli scaffolding, so go directly to the official documentation to find the configuration
Solution method
Create a vue.config.js under the package.json sibling folder and configure it as follows
Module.exports = {devServer: {proxy: {'/ api': {target: 'url', / / set the domain name and port number to access changeOrigin: true / / set to cross-domain pathRewrite: {'^ / api':'/'/ here it means to replace the address in target with'/ api' When the request is initiated later, / api will replace the value in target, and cross-domain} can be realized.
Modify our request code
Axios.get (`/ api/app.do?method=authUser&xh=$ {this.sNo} & pwd=$ {this.password}`) .then (res) = > {/ /.}) .catch ((err) = > {/ /.})
Here / api is used to replace the original url to achieve cross-domain
Axios initiates post request the backend cannot receive data
When I sent the post request to the background using axios for the first time, I found that the backend did not receive the data I sent, and the backend used the spring framework, but I tested the same request with my own node server.
Original code
Axios.post (url, {data:data}) .then (res = > {/ /.}) .catch (err = > {/ /.})
I can get {"data": 1} when I use the node server to print the data that has been pulled by requests, but only null is always available at the back end.
After looking at the front and back end code, I always feel that there is no problem, and the only variable is axios, so go to Taobao image to see the use of axios and see an overview of the features.
That is to say, the data in the request and the data in the response can be formatted, and the json data will be converted automatically. I try to change the above request to use a non-json format.
Axios.post (url, `data=$ {data} `) .then (res = > {/ /.}) .catch (err = > {/ /.})
Unexpectedly successful, then why, after consulting the data, finally found the corresponding source code on GitHub
TransformRequest: [function transformRequest (data, headers) {normalizeHeaderName (headers, 'Accept'); normalizeHeaderName (headers,' Content-Type') If (utils.isFormData (data) | | utils.isArrayBuffer (data) | | utils.isBuffer (data) | | utils.isStream (data) | | utils.isFile (data) | | utils.isBlob (data)) {return data } if (utils.isArrayBufferView (data)) {return data.buffer;} if (utils.isURLSearchParams (data)) {setContentTypeIfUnset (headers, 'application/x-www-form-urlencoded;charset=utf-8'); return data.toString () } / / look here-- if (utils.isObject (data)) {setContentTypeIfUnset (headers, 'application/json;charset=utf-8'); return JSON.stringify (data);} return data }]
When determined as an object, headers will be set to application/json Charset=utf-8, that is, Content-Type, and according to the back-end students in the project team, the server requires Content-Type': 'application/x-www-form-urlencoded. I tried to set headers to application/x-www-form-urlencoded before sending the request, but it didn't work, probably because the changes to headers in the source code were implemented after my own settings, but if you write this, you have to write a long string. If you feel troublesome, you can try the following methods
Because the headers is modified through transformRequest in the source code, and we can actually implement this method ourselves, we just need to implement this method ourselves when sending the request. Here, we can achieve this goal by modifying the data structure of data.
Import Qs from 'qs'axios ({url:url, data: {data:data}, transformRequest: [function (data) {/ / modify the data format of data return Qs.stringify (data)}] Headers: {'deviceCode':' A95ZEF1-47B5murAC90BF3'}) .then (res = > {/ /.}) .catch (err = > {/ /.})
The above is to convert the data format of data, but we can also choose to modify the way data is handled.
Axios ({url:url, data: {data:data}, transformRequest: [function transformRequest (data, headers) {normalizeHeaderName (headers, 'Accept'); normalizeHeaderName (headers,' Content-Type') If (utils.isFormData (data) | | utils.isArrayBuffer (data) | | utils.isBuffer (data) | | utils.isStream (data) | | utils.isFile (data) | | utils.isBlob (data)) {return data } if (utils.isArrayBufferView (data)) {return data.buffer;} if (utils.isURLSearchParams (data)) {setContentTypeIfUnset (headers, 'application/x-www-form-urlencoded;charset=utf-8'); return data.toString () } / / look here-- if (utils.isObject (data)) {setContentTypeIfUnset (headers, 'application/x-www-form-urlencoded;charset=utf-8') Let _ data = Object.keys (data) return encodeURI (_ data.map (name = > `${name} = ${data [name]}`). Join ('&');} return data }]) .then (res = > {/ /...}) .catch (err = > {/ /.}) these are all the contents of the article "how to use axios to send post requests in vue cli3 projects". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to 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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.