When the parameter is JSON对象 , the default content-type is Application/json.
axios.post(‘/user‘, { firstName: ‘Fred‘, lastName: ‘Flintstone‘ }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
The parameter passed at this time is request payload format {firstName:"Fred",lastName:"Flintstone"}
If No ‘Access-Control-Allow-Origin‘ header is present on the requested resource An error occurs, it is a cross-domain issue. I like to directly configure the server to solve cross-domain: For example nginx configuration: Nginx configuration cross-domain request
When the parameter is a JSON string , the default content-type is application/x-www-form-urlencoded.
axios.post ('/user ', json.stringify ({firstName: ' Fred ', lastName: ' Flintstone '}). Then (function ( Response) {Console.log (response); }). catch (function (error) {Console.log (error); });
The parameter passed at this time is form data format key:value :
{"FirstName": "Fred", "LastName": "Flintstone"}:
As above. In fact, this is an invalid data, key is {"FirstName": "Fred", "LastName": "Flintstone"} , value is empty.
To use the application/x-www-form-urlencoded format, data conversion is required, although there are two ways URLSearchParams and qs two ways. I prefer qs库 the way to use the code as follows:
axios.interceptors.request.use((req) => { if (req.method === ‘post‘) { req.data = qs.stringify(req.data); } return req;}, (error) => Promise.reject(error));
When you use Axios, you only need to pass the JSON object:
axios.post(‘/user‘, { firstName: ‘Fred‘, lastName: ‘Flintstone‘ }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
Axios request JSON questions in a detailed