Axios post submits an instance of formdata, axiosformdata

Source: Internet
Author: User

Axios post submits an instance of formdata, axiosformdata

Axios is recommended for the vue framework to send ajax requests.A blogTo explain how to use axios In the vue component. However, the get requests were used for previous purposes. Now I used the post method when I set up my own blog. I found that the backend (node. js) could not get any parameters from the front-end. After some exploration, I finally found the problem.

Four encoding methods for post data submission

1. application/x-www-form-urlencoded

This should be the most common post encoding method. This method is used by default for normal form submission. Most server languages have good support for this method. In PHP, you can use $ _ POST ["key"] to obtain the key value. In node, you can use querystring middleware to separate parameters.

app.post("/server",function(req,res){ req.on("data",function(data){ let key=querystring.parse(decodeURIComponent(data)).key; console.log("querystring:"+key) });});

2. multipart/form-data

This is also a common post data format. When using a form to upload a file, you must make the form's enctype attribute or the ajax contentType parameter equal to multipart/form-data. The data sent to the background in this encoding format looks like this

Different fields start with -- boundary, followed by the content description, and finally the specific content of the field. If a file is transmitted, it also contains the file name and file type information.

3. application/json

By default, axios uses this format for submission. If this encoding method is used, the serialized json string is passed to the backend. We can compare the data sent by application/json with application/x-www-form-urlencoded.

Application/json:

Next is application/x-www-form-urlencoded:

Here we can see that the data uploaded by application/x-www-form-urlencoded to the background is organized in the form of key-value, while application/json is a json string directly. If application/x-www-form-urlencoded is still used in the background when processing application/json, the problem may occur.

For example, if the background node. js still uses the method of dealing with application/x-www-form-urlencoded, the data obtained after querystring. parse (decodeURIComponent (data) is like this.

At this time, querystring. parse (decodeURIComponent (data). key can only get undefined

4. text/xml

The remaining encoding format is text/xml, which I have never used.

Solution

Since we know that the axios post method uses the application/json format to encode data by default, there are two solutions: one is to change the method of receiving parameters in the background, the other is to change the encoding format of the axios post method to application/x-www-form-urlencoded, so that no modifications are required in the background.

First, let's look at the first solution.

In the vue component, the code used by axios to send a post request is as follows:

this.$axios({ method:"post", url:"/api/haveUser", data:{ name:this.name, password:this.password }}).then((res)=>{ console.log(res.data);})

In this case, the information in the console Network Headers is like this.

The backend needs to rely on the body-parser middleware to receive data. We have installed it in advance and then reference the body-parser in the background code.

In this example, the code is only const bodyParser = require ("body-parser ");

Next, use the body-parser in the route.

app.post("/api/haveUser",bodyParser.json(),function(req,res){ console.log(req.body); let haveUser=require("../api/server/user.js"); haveUser(req.body.name,req.body.password,res);});

At this time, after the current station sends a post request, the background console will print the req. body

In this case, the corresponding value can be obtained through req. body. name or req. body. password.

This method is relatively simple and does not require too many changes on the front end. We recommend that you use this method.

The second solution is as follows:

Front end

this.$axios({ method:"post", url:"/api/haveUser", headers:{ 'Content-type': 'application/x-www-form-urlencoded' }, data:{ name:this.name, password:this.password }, transformRequest: [function (data) { let ret = '' for (let it in data) {  ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&' } return ret }],}).then((res)=>{ console.log(res.data);})

Headers and transformRequest play a key role. Headers is the custom request header to be sent. TransformRequest allows you to modify the request data before sending it to the server. After this operation, the backend querystring. parse (decodeURIComponent (data) obtains an object similar to {name: 'w', password: 'W.

The background code is as follows:

app.post("/api/haveUser",function(req,res){ let haveUser=require("../api/server/user.js"); req.on("data",function(data){  let name=querystring.parse(decodeURIComponent(data)).name;  let password=querystring.parse(decodeURIComponent(data)).password;  console.log(name,password)  haveUser(name,password,res); });});

This method is obviously more troublesome than the first one, but does not need to be processed in the background. Therefore, the specific operation depends on the actual situation.

The above example of submitting formdata in axios post is all the content shared by Alibaba Cloud xiaobian. I hope to give you a reference and support for the help house.

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.