This is the 13th day of my participation in the August More text Challenge. For details, see: August More Text Challenge

1. Axiox profile

In the jquery era, we used Ajax to submit data requests to the background, and in the Vue era, Axios provides various ways for the front end to request data from the background.

A lot of vUE uses Axios.

The advantages and disadvantages:

  • Create an HTTP request from Node.js
  • Supporting Promise API
  • The client supports CSRF prevention
  • Provides some interfaces for concurrent requests (important, much easier)

2. The cross-domain axios

Because the port numbers of the front and back ends are different, cross-domain problems may occur. There are many general methods to solve cross-domain problems, such as using background configuration or nginx. The following is a demo I have done.

1. Configure cross-domain nGINx

#user nobody; worker_processes 1; #error_log logs/error.log; #error_log logs/error.log notice; #error_log logs/error.log info; #pid logs/nginx.pid; daemon off; events { worker_connections 65535; multi_accept on; } http { include mime.types; default_type application/octet-stream; #log_format main '$remote_addr - $remote_user [$time_local] "$request" ' # '$status $body_bytes_sent "$http_referer" ' #  '"$http_user_agent" "$http_x_forwarded_for"'; #access_log logs/access.log main; sendfile on; tcp_nopush on; tcp_nodelay on; #keepalive_timeout 0; keepalive_timeout 65; server { listen 8080; server_name localhost; Location = / {proxy_pass http://localhost:8088; / {proxy_pass http://localhost:8088; } ## /no = /no1,no/son, "No /son/grandson /grandson ## if proxy_pass ends with/like http://localhost:3000/; Match/no son, then the real match for http://localhost:3000/son, the location/no {proxy_pass http://localhost:8088; } ## /ok/ location /Demo/testDemoTranNew {proxy_pass http://localhost:8088; }}}Copy the code

2. Configure the AXIOS cross-domain configuration

You can also configure cross-domains in AXIOS as follows:

1. Modify the config/index.js file
// Add cross-domain proxyTable: {"/ API ": {// target address: "http://localhost:8088", changeOrigin: true, pathRewrite: {'^/ API ': "'}}},Copy the code
2. Add variables to main.js
Vue.prototype.HOST = '/ API 'Copy the code

Call directly can, completely avoid cross-domain!

3. Get request from Axios

Main.js needs to import the AXIOS component when used. For details, see the following section.

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import axios from "axios"


Vue.config.productionTip = false

Vue.prototype.$axios = axios

/* eslint-disable no-new */
new Vue({
    el: '#app',
    router,
    components: { App },
    template: '<App/>'
})
Copy the code

Get request in vue. There are two ways to write, and the format of the two ways is attached below.

<template> <div> {{data}} </div> </template> <script> export default { name: 'HelloWorld', data () {return {content:" component 1", data:{}}}, methods:{}, Created () {/ / / / the first one enclosing $axios. Get (" https://api.apiopen.top/searchMusic ", {/ / params: {/ / name: "fit" / /} / /} / /) // .then(res => { // console.log(res) // this.data = res.data // }) // .catch(error => { // console.log(error) // }) // The second enclosing $axios ({method: "get", url: 'https://api.apiopen.top/searchMusic', params: }}).then(res => {console.log(res) this.data = res.data}).catch(error => {console.log(error)}); } } </script>Copy the code

4. Post request from Axios

There are also two ways to write in the call. Note that you need to use QS to format the parameters because you need to convert the object to JSON format.

<template> <div> {{data}} </div> </template> <script> import qs from "qs" export default { name: 'HelloWorld', data () {return {content:" component 1", data:{}}}, methods:{}, Created () {// Axios receives post requests with form-data format ---- name = xiaobao needs to use qs // this.$axios.post("https://api.it120.cc/common/mobile-segment/next",qs.stringify( // { // segment: 0 // } // ) // ) // .then(res => { // console.log(res) // this.data = res.data // }) // .catch(error => { // Console.log (error) //}) // This method requires transformRequest to convert the format. Otherwise, an error will be reported because it accepts a string argument this.$axios({ method: 'post', url: 'https://api.it120.cc/common/mobile-segment/next', data: { segment: 0 }, transformRequest: [function (data) {return qs.stringify(data);}]}).then(res => {console.log(res) this.data = res.data }) .catch(error => { console.log(error) }); } } </script>Copy the code

5. Global URL configuration

Because if you call the same API prefix, you can use global configuration to make the URL global and avoid writing it more than once.

To configure main.js as needed here, attach the code below.

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import axios from "axios"


Vue.config.productionTip = false

Vue.prototype.$axios = axios

axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

/* eslint-disable no-new */
new Vue({
    el: '#app',
    router,
    components: { App },
    template: '<App/>'
})
Copy the code

When called, the URL can omit the configuration in baseURL

6. The interceptor

Before axios sends and accepts, the interceptors (similar to Java interceptors) are executed, which needs to be configured in main.js.

// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import router from './router' import axios from "axios" import qs from 'qs' Vue.config.productionTip = false Vue.prototype.$axios = axios axios.defaults.baseURL = 'https://api.it120.cc'; //axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; //axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; / / add request interceptor axios. Interceptors. Request. Use (function (config) {/ / do something before sending a request the console. The log (config) if (config. The method = = = "post") { config.data = qs.stringify(config.data); } return config; }, function(error) {// do something about the request error return promise.reject (error); }); / / add the response interceptor axios. Interceptors. Response. Use (function (response) {the console. The log (response) if (the response status! == 200) { return; } // Do something about the response data return response; }, function(error) {// do something about the response error return promise.reject (error); }); /* eslint-disable no-new */ new Vue({ el: '#app', router, components: { App }, template: '<App/>' })Copy the code

In this way, we intercept the QS method for the rest of our use, so we don’t have to call the QS method on every request.

<template> <div> {{data}} </div> </template> <script> import qs from "qs" export default { name: 'HelloWorld', data () {return {content:" component 1", data:{}}}, methods:{}, $axios({method: 'POST ', url: '/common/mobile-segment/next', data: {segment: 0 } }) .then(res => { console.log(res) this.data = res.data }) .catch(error => { console.log(error) }); } } </script>Copy the code

7. Front end test method

There are several ways to get data on the test front end

  • 1. The mock request has its own JSON format drawback: it cannot post the request
  • 2. Set up a server to obtain data
  • 3. Disadvantages of using data that already exists online: Data must exist online

Attention! When operating the DOM node, avoid operating the native DOM as follows:

<template> <div> {{data}} <p ref = "myp">aaa</p> </div> </template> <script> import $ from "jquery" export default { name: 'HelloWorld', data () {return {content:" component 1", data:{}}}, methods:{}, Mounted () {// dom console.log(this.$refs.myp.innerhtml = "BBB") //console.log(this.$refs.myp.style.color = "red") Var myo2 = this.refs.myp myo2.addeventListener ("click",function(){console.log("666")} $(myo2).css("color","YELLOW"); } } </script>Copy the code