Post Four encoding methods for submitting data

1. Application/X-www-form-urlencoded This should be the most common POST coding method, common form submission is submitted in this way by default. Most server languages have good support for this approach. PHP uses $_POST[“key”] to retrieve the key value, while Node uses queryString middleware to separate the parameters

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

This is also a common post data format. When you upload a file using a form, you must set the encType property of the form or the contentType parameter of the Ajax form to be equal to the multipart/form-data. The data that goes into the background with this encoding format looks something like this

Different fields start with –boundary, followed by the content description information, and finally the specific content of the field. If you are transferring a file, also include the filename and file type information

3. This format is used for the application/ JSON AXIos default submission. If you use this encoding, the serialized JSON string is passed to the background. We can compare application/json with application/x-www-form-urlencoded data.

Application/X-www-form-urlencoded:

It can be clearly seen that application/ X-www-form-urlencoded data uploaded to the background is organized in the form of key-value, while Application/JSON is directly a JSON string. It would be a problem if the background was coded for Application/JSON like Application/X-www-form-urlencoded. Parse (decodeURIComponent(data)) queryString.parse (decodeURIComponent(data)) will look like this if node.js still does application/ X-www-form-urlencoded method

Querystring.parse (decodeURIComponent(data)).key

4. Text/XML One of the remaining encoding formats is text/ XML, which I haven’t used much

The solution

Now that we know that the AXIos POST method encodes data in application/ JSON format by default, there are two solutions. One is to change the received 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 background changes are required. In the first solution, the VUE component, axios sends a POST request in the following code

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

Now the message inside the console Network Headers looks something like this

Background data needs to be relied onbody-parserMiddleware, which we pre-installed, and then referenced body-Parser in the background code

In this screenshot, only const bodyParser=require(“body-parser”); Next, use 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); });Copy the code

At this point, after the console sends a POST request, req.body is printed in the background console

In this case, either req.body.name or req.body.password will fetch the corresponding value. This method is relatively simple and does not require much modification by the foreground. It is recommended to use this method.

The second solution is as follows

The 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);
})
Copy the code

Headers and transformRequest play key roles. Headers sets the custom request header to be sent. TransformRequest allows you to modify the request data before sending it to the server. Querystring.parse (decodeURIComponent(data)) returns objects like {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); }); });Copy the code

This method is obviously a bit more cumbersome than the first, but does not require much processing in the background. So the specific operation has to be decided according to the actual situation.