Today, when I was adjusting the interface, I found that when I submitted the data in formData format by axiOS Post, the request turned into opition, resulting in the failure of the request. This frustrated me, because I can use jQuery $. Ajax request success, no problem, data returned successfully. So I went to the Internet search, finally solved! Let me analyze it:

An error condition

Console requests are now OPITIONS



But I wrote POST



Why is that? Specific reasons can refer to AJAX cross-domain request OPTIONS method, I think it is very detailed, next, I talk about my solution 😄

The solution

1. Use URLSearchParams (compatibility issues, more trouble to write)

var data = new URLSearchParams();
data.append('id'.'1');
data.append('name'.'minmin');
data.append('age'.'23')... postData(data).then( res => { ... })Copy the code

PostData here is the method THAT I wrote directly, but if it’s axios that’s not wrapped, just pass it the way it was written

axios.post('url, data).then( res => { ... })Copy the code

2. Use the qs. Stringify

1. Install

CNPM install --save axios vue-axios qs --save axios vue-axios QSCopy the code

2. Axios configuration

I wrote the AXIos configuration in SRC /utils/request.js, and introduced qs and configured it in my current request.js



In these two places above qs, introduced according to my writing, and in axios. Interceptors. Request. Use request before judge if it is a post request will data qs. Stringify

import qs from 'qs'
Copy the code

axios.interceptors.request.use((config) => {
  if(config.method  === 'post'){
    config.data = qs.stringify(config.data);
  }
  return config;
},(error) =>{
  return Promise.reject(error);
});
Copy the code

So it’s ok to pull, so you don’t have to worry about the request mode there is opitions, so let’s go to the console and check it out, that’s great, reward a small hair

If there is no encapsulation of the AXIOS configuration, it can be introduced directly after

axios.post('url, qs.stringify(data)).then( res => { ... })Copy the code

Problems encountered

Do you think this is done? No, no, no, because my request is to send a lot of Chinese to the background, after the success of sending, I found that the value returned to me is a bunch of gibberish, wrong ah! That’s not right! Look at your interface to wear the parameters clearly is Chinese how the fuck back to become garbled, this… I looked for the problem again and found that all I had to do was add a line of code to the AXIos configuration

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';Copy the code



Finally request interface try again, garbled code disappeared, done!

I personally recommend using this method of QS, because it is more convenient to use, each append is too troublesome ~

Next time, axios configuration! Ha ha 😄