Demonstrate the basic use of AXIOS with node back-end code, and get more familiar with the application of HTTP requests in front-end projects by switching between front-end and back-end codes.

Software version

  • Express: 4.17.1
  • Axios: 0.21.1

Create the back-end environment

Use Express to implement the test background

The business code is only in app.js and implements GET and POST requests in the first layer of routing

HTTP file is a REST Client using cURL command to test the interface

Creating a front-end environment

Here I am lazy to import AXIos and QS directly through the link, without the help of other frameworks

Tips: You can preview the page here using the Live Serve plugin

Function implementation

A GET request
  • The background part
    • Use firstexpressImplement a simplegetrequest
    app.get('/user'.(req, res) = > {
       res.send('Hello World! ' + req.query.ID)
    })
    Copy the code
    • Curl test interface
    GET http://192.168.3.108:3000/user? ID=12345Copy the code
  • The front part
    • Import using unPKG CDNaxios
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    Copy the code
    • Create one of the simplestgetrequest
    function getTest() {
      axios.get('http://localhost:3000/user? ID=12345')
          .then(function (response) {
          // Handle success
          console.log(response);
      })
          .catch(function (error) {
          // Handle error cases
          console.log(error);
      })
          .then(function () {
          // Always execute})}Copy the code

tips: I thought I could directly request to the interface, but the request found that there was a cross-domain problem, because here Live Serve is to create a service on port 5500, while the interface of our local service is 3000, so there was a cross-domain problem, so I directly opened the interface in the Express program, the code is as follows:

app.all("*".function(req,res,next){
  * indicates that any domain name is allowed to cross domains
  res.header("Access-Control-Allow-Origin"."*");
  // The allowed header type
  res.header("Access-Control-Allow-Headers"."content-type");
  // The type of requests that are allowed across domains
  res.header("Access-Control-Allow-Methods"."DELETE,PUT,POST,GET,OPTIONS");
  if (req.method.toLowerCase() == 'options')
    res.send(200);  // Let options try to end the request quickly
  else
    next();
});
Copy the code
A POST request

In POST request, two methods are generally used, one is in the form of JSON data and the other is in the form of form data. If the front and back ends are inconsistent, it is impossible to adjust them. Because of this, the front and back ends often have errors in POST requests. Here we separately test json data form data.

  • jsonPOST requests for data
    • In the background, we need to add JSON parsing
    app.use(bodyParser.json());
    Copy the code
    • Accept the POST route directly
    app.post('/secret'.function (req, res) {
        console.log(req.body)
        res.send({
           msg: 'success'})})Copy the code
    • Test the request, note the blank line here
    POST http://192.168.3.108:3000/secret
    Content-Type: application/json
    
    {
       "name": "foo",
       "password": "bar"
    }
    Copy the code
    • The front end makes a POST request
    function postJSONTest() {
      axios.post('http://192.168.3.108:3000/secret', {
          name: 'CODE',
      }) 
          .then(function (response) {
          console.log(response);
      })
          .catch(function (error) {
          console.log(error);
      });
    }
    Copy the code
  • form dataPOST requests for data
    • Join the sameformParsing, route unchanged
    app.use(bodyParser.urlencoded({
        extended:true
    })); 
    Copy the code
    • The test interface
    POST http://192.168.3.108:3000/secret
    Content-Type: application/x-www-form-urlencoded
    
    name=foo
    &password=bar
    Copy the code
    • The front-end request
    function postFORMTest() {
      axios.post('http://192.168.3.108:3000/secret',
                 qs.stringify({ name: 'CODE'{}),headers: {'Content-Type':'application/x-www-form-urlencoded'}}) 
          .then(function (response) {
          console.log(response);
      })
          .catch(function (error) {
          console.log(error);
      });
    }
    Copy the code

This is because without serialization, the backend gets the whole object, not the actual object

conclusion

So far, the most basic test of using AXIos has been completed. Of course, this is the most basic and simplest use. There is still a certain distance to use axios in the project.