Axios request JSON questions in a detailed

Source: Internet
Author: User

  • 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

    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.