Vue axios cross-domain requests and associated processing

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed.

axios Overview

axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。

* 从浏览器中创建 XMLHttpRequests
* 从 node.js 创建 http 请求
* 支持 Promise API
* 拦截请求和响应
* 转换请求数据和响应数据
* 取消请求
* 自动转换 JSON 数据
* 客户端支持防御 XSRF
复制代码

Use axios Call Interface

Since vue-cli cross-domain to the requested address is formed using a cross-domain vue-cli3 solution as follows:

需要在开发环境下将 API 请求代理到 API 服务器。通过 vue.config.js 中的 devServer.proxy 选项来配置。
复制代码
  1. Installation Axios npm install axios, after the installation is completed to see if the dependent is formed Axios package.json.

2. Create a vue.config.js under the root directory of the code written proxy

module.exports = {
  configureWebpack: {
      devServer: {
          proxy: {
              //名字可以自定义,这里我用的是api
              '/api': {
                target: 'http://localhost:80',//设置你调用的接口域名和端口号 别忘了加http
                changeOrigin: true,//这里设置是否跨域
                pathRewrite: {
                  '^/api': ''
                }
              }
          }
      }
  },
}

复制代码
  1. Asynchronous request send a request using axios
axios.get("/api/myphpTest/demo.php")
        .then(function(response) {
          console.log(response);
        })
        .catch(function(error) {
          console.log(error);
        });
    }
复制代码

Reproduced in: https: //juejin.im/post/5cf07f4de51d4510b71da59a

Guess you like

Origin blog.csdn.net/weixin_34007879/article/details/91475867