Cross-domain issues
Using VUE django to separate front and back, cross-domain and django CSRF tokens is a very headache problem. There are many solutions to cross-domain problems. There are many bings here to skip them. Let’s talk about the usage of tokens. Cancel token detection. Django development is mentioned here.
Django front and back separation CSRF acquisition and use
First, we need to obtain the CSRF token. The GET request in django will not perform CSRF verification. Here we can create a django view, and the front-end can obtain it through the GET request.
Django configuration
1. Get the token view
Here I wrote two:
- The first is to send a GET request directly to obtain it
- The second is to pass the token and the information required for login to the front end when the server handles the login request.
Why do I think about it two things? It is because I am lazy. If both use the first one, the backend needs to process the json data, and directly copy and pass the token string, encapsulate it into json to the frontend.
def get_csrf_token(request): csrf_token = get_token(request) print(csrf_token) return JsonResponse({'csrfToken': csrf_token}) # return csrf_token def get_csrf_token1(request): csrf_token = get_token(request) print(csrf_token) return csrf_token
2. The backend settings configuration file needs to be configured with the following information.
CORS_ALLOW_HEADERS = [ 'XMLHttpRequest', 'X_FILENAME', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', 'Pragma', # Add other request headers you need, there are more] MIDDLEWARE = [ '', #Put it in front '', '', '', '', #And this '', '', '', 'sbh_bly_api.', ] # Configuring the trust domain of CSRF is the same as cross-domain configuration. This is very important. I have been stuck for a day because of thisCSRF_TRUSTED_ORIGINS = [ 'http://127.0.0.1:8080', # Make sure to match the front-end address]
3. VUE front-end configuration
Pay attention to the ts used in my VUE project. If you use js, please convert it yourself.
1) Axios encapsulation, here the encapsulation file is made for the axios request. The code here stores the token in the store. Here the value "const token =" determines the storage location according to the actual project and habits.
// import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'; import store from '@/store'; // Create an Axios instanceconst instance: AxiosInstance = ({ baseURL: 'http://127.0.0.1:8000', headers: { 'Content-Type': 'application/json' }, }); // Request an interceptorimport axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'; import store from '@/store'; // Create an Axios instanceconst instance = ({ baseURL: 'http://127.0.0.1:8000', timeout: 3000, headers: { 'Content-Type': 'application/json' }, }); // Request related processing Request interception In request interception, the request related configuration can be supplemented// Interceptors axios interceptor object(config => { // config all information requested // (config); const token = ['X-CSRFToken'] = token return config // Return the configured config object if it does not return, the request will not proceed}, err => { // Related processing when an error occurs in the request throws an error(err) }) (res => { // We usually process it here. The error status code after the request is successful. For example, the status code is 500, 404, 403 // res is all the corresponding information (res) return (res) }, err => { // Handling when an error occurs in the server response (err) }) export default instance;
2) Configuration item, send a request header when opening axios request in main
import axios from 'axios'; = true;
3) Get request to obtain the token
import axios from '@/http' const get_token = () => { ("aa") var post_data = ({ username: "123", password: "1234" }) axios({ method: 'GET', url: + '/api/get-csrf-token/', data: post_data }) .then(function (response) { () // const token = ('=')[1]; //The request is successful, processing business logic () // =token // Save token = }) .catch(function (error) { //Request failed, processing business logic (error) }) }
If it is not successful, please leave a message and we will solve it together
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.