Learning Chapter 3 of Django+Vue project: use axios to send get requests, solve cross domain problems, and call the front and back ends

Portal:

Django+Vue project learning part 1: django background construction

Django+Vue project learning part 2: vue project creation  

Through the first two articles, the back-end and front-end shelves have been set up, and the back-end has written the method return data. This article will introduce in detail how to use axios to send get requests and solve the cross domain problem of django+vue

The front page is as follows

First analyze my needs:

(1) I want to click different buttons to trigger different requests. For example, clicking [mobile phone number] will call the method of generating mobile phone number in the background; Click ID card ID to call the method of generating ID in the background;

(2) At present, there are three buttons on the page that need to bind events to trigger background requests. It is best that the three buttons can bind the same event to distinguish which request is called by judging which button is clicked;

(3) The textarea tag displays the data returned from the background;

(4) There is an input box behind the [ID card ID] and [person name] buttons. I need to obtain the value of the input box and send it to the back end;

The following is in main_ Write code in page.vue to realize the above requirements

1. Define the parameters for receiving two input tags and the parameters for textera tags

Define three parameters under the data() function. num1, num2 and info represent two input input boxes and textera labels respectively

<script>
export default {
  name: "main_page",
  data() {
    return {
      num1: null, // The default value is set to null
      num2: null,
      info: null,
    }
  },
}
<script/>

Use v-model in the input tag to bind num1 and num2 in both directions

In this way, the num1 and num2 parameters can receive the input value of the input tag

......
<input class="input_style" type="text" name="card_id" id="id_num" value="" placeholder="Please enter the number" v-model="num1">
......
<input class="input_style" type="text" name="name" id="name_num" value="" placeholder="Please enter the number" v-model="num2">
......

After the front end sends the request and obtains the response data, it can assign the response content to the info parameter and display the info content to textera through Mustache syntax, so the code is as follows

......
<div><textarea class="textera" id="result">{{info}}</textarea></div>
......

2. Determine which button the front-end clicks to trigger different requests

If you want to know which button the front-end clicks, you can pass in the event parameter when defining the function to obtain the event object of the browser

Define a function under methods   create_data(event) function, which passes in a parameter event

<script>
export default {
  name: "main_page",
  data() {
    return {
      num1: null,
      num2: null,
      info: null,
      // CsrfToken: token()
    }
  },
  
  methods: {
    
    create_data(event) {
      console.log('Click the of the element id='+event.target.id) //Print and see the results
      
      if (event.target.id === "b01") {  //adopt event.target.id,Get the click events monitored by the browser, and view the click elements id,By comparison id Value to determine which request is triggered
        ......
        ......
        ......
      } else if (event.target.id === "b02") {
        ......
        ......
        ......
      } else if (event.target.id === "b03") {
        ......
        ......
        ......
      }
    }
  }
}
</script>

In the corresponding html code, when binding an event to a button, you need to pass in $event, as shown below

......
<div class="b1"><button type="button" id="b01" @click="create_data($event)">phone number</button></div>
......
<button  type="button" id="b02" @click="create_data($event)">ID ID</button>
......
<div class="b1"><button type="button" id="b03" @click="create_data($event)">name</button>

Run the code and have a look   console.log('click on the element id='+event.target.id) to print the result

It is really the id attribute "b01" I defined for the button [mobile phone number]

So we can judge which button the front-end clicked in this way

3. Send get request using axios (without parameters)

Install axios first and enter the installation command at the terminal

npm install axios

  In create_ Add axios sending request code in the data () function. First, implement a get request without parameters: generate a phone number

<script>
import axios from 'axios'

export default {
  name: "main_page",
  data() {
    return {
      num1: null,
      num2: null,
      info: null,
    }
  },

  methods: {

    create_data(event) {

      if (event.target.id === "b01") {  //adopt event.target.id,Get the click events monitored by the browser, and view the click elements id,By comparison id Value to determine which request is triggered
        axios({
          url: "http://localhost:8000/create_data/phone"  //If not specified method,Default send get request
        }).then(res => {
          this.info = res.data
          console.log(res)

        })
      }
    }
  }
}
</script>
  • Where the url is written is the route configured by the backend [generate phone number];
  • this.info = res.data, indicating that the request result is output to the info parameter;

If not only the request method is specified, axios sends the get request by default, so it is simply written here

Because we have bound the event to the button. After writing the code, click the [mobile phone number] button on the front end, and the following results appear

 

After checking the following information, it indicates that a cross domain problem has occurred: the front end is written in vue, the server port is 8080, the back end is written in django, and the server port is 8000. We are calling the back-end service through the front end, resulting in a cross domain request (please find the information for the specific meaning)

4. Solve cross domain problems

Under the django project, install a third-party package to solve the cross domain problem

pip install django-cors-headers

Related configuration

Open settings.py

INSTALLED_APPS = [
    'create_data',
    'polls',
    'study_models_app',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'corsheaders',  # Add this line of configuration
]
MIDDLEWARE = [

    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',  # The new line of configuration is said to be placed here on the Internet, so we also put it here
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',  
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
CORS_ORIGIN_ALLOW_ALL = True # Add this line to allow any domain access

In fact, after completing the above configuration, you can access the get request, but there are other general configurations, which do not matter

# Allowed request headers
CORS_ALLOW_HEADERS = [
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
]
# Permissible http request
CORS_ALLOW_METHODS = [
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
]

Try again. You can call the request normally to get the return data

This article comes here first. It mainly talks about how the front end binds events and sends a simple get request using axios, and solves the cross domain problem

The next article continues to say that the get request is sent, but the parameters will be carried in the request

Several reference blog posts are attached:

http://www.axios-js.com/docs/#axios-get-url-config

https://www.jianshu.com/p/007fe1a6f444

https://www.cnblogs.com/bdxily/p/14642152.html

https://blog.csdn.net/haeasringnar/article/details/80868534

 

Posted by d0rr on Tue, 23 Nov 2021 22:48:06 -0800