Problems in the application of Axios

Keywords: axios JSON Vue less

1. Set Axios cross domain in Vue

axios has become the officially recommended way for Vue to obtain background data from ajax. However, we need to solve the cross domain problem of axios in use. Here we take the 2.x version of Vue cli as an example to solve the cross domain problem of axios.

In config/index.js
We implement the proxy by setting the proxyTable of the dev configuration

dev: {

    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      '/api': {
        target: 'http://127.0.0.1:3000/',//Set the domain name and port number of the interface you call. Don't forget to add http
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''     //Here it is understood that "api" is used instead of the address in target. In the following components, when we drop the interface, we directly use api instead. For example, I need to call "http://127.0.0.1:3000/user/add" and write "api/user/add" directly
          //Or we can continue to look at it without adding api
        }
      }
    }
  },

Then bind the path of dev environment in config/dev.env.js
(note that it's a pattern like 'development'; don't use less quotation marks.)

module.exports = merge(prodEnv, {
  NODE_ENV: '"development"',
  API_HOST: '"/api"'  //The api here is the http://127.0.0.1:3000 configured above/
})

Then bind the path of production environment in config/prod.env.js

module.exports = merge(prodEnv, {
  NODE_ENV: '"production"',
  API_HOST: '"https://www.baidu.com"'  //Your real online address
})

In the unified configuration file of axios
Different interface paths will be automatically matched according to different environments

import axios from 'axios';
const baseURL = process.env.API_HOST;    // Interface prefix for the current environment
get(url, params) {  // get
    return axios({
      method: 'get',
      baseURL: baseURL,     //Interface path of current environment
      url,
      params,    // Parameters with get request
      timeout: 5000,
      headers: {
        'X-Requested-With': 'XMLHttpRequest'
      }
    }).then(
      (response) => {
        return checkStatus(response);
      }
    )
  }

2. Use axios to forge referer

Jsonp is the most common cross domain solution, and it is the most compatible solution. When we usually grab data, we will simulate the request of jsonp, but for the sake of security, the request of jsonp will be verified by the referer, so we need to forge the referer.

We should have requested it directly from jsonp, but now we need to add a layer of agent in the background

ajax.js

import axios from 'axios';  //Introducing axios
export function getDiscList() {
  const url = '/api/getDisList'; //Address we requested (to our back office agent)
 // parameter
  const data = Object.assign({}, commonParams, {
    platform: 'yqq',
    hostUin: 0,
    sin: 0,
    ein: 29,
    sortId: 5,
    needNewCode: 0,
    categoryId: 10000000,
    rnd: Math.random(),
    format: 'json'  // Because it is a jsonp request, it will return the request format of jsonp. Because we use a proxy, we change the return format to json
  });

 // Using axios to request from agents
  return axios.get(url, {
    params: data
  }).then((res) => {
    return Promise.resolve(res.data);
  });
};

In the webpack.dev.conf.js file of build

const axios = require('axios');
const express = require('express');
const app = express();
devServer: {
    before(app) {
        //axiosd calls the address of the agent and triggers a callback function to call the address of the real data
      app.get('/api/getDisList', function (req, res) {
          //Address of the actual fetched data to be called
        var url = 'https://c.y.qq.com/splcloud/fcgi-bin/fcg_get_diss_by_tag.fcg';
        axios.get(url, {
            //Set the header, change the referer and host of the request
          headers: {
            referer: 'https://c.y.qq.com/', 
            host: 'c.y.qq.com'
          },
          params: req.query
        }).then((response) => {
          res.json(response.data); //The response is returned from the api address, and the data is in data.
        }).catch((err) => {
          res.json({
              code: '2',
              message: err
          })
        })
      })
    }
}

Finally, you can call it directly

import {getDiscList} from './ajax.js';
export default {
  data() {
    return {
    };
  },
  methods: {
    _getDiscList() {
      getDiscList().then((res) => {
        console.log(res);
      });
    }
  },
  created() {
    this._getDiscList();
  }
};

Posted by Gregghawes on Mon, 06 Jan 2020 04:37:26 -0800