惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
G
Google Developers Blog
S
SegmentFault 最新的问题
Microsoft Security Blog
Microsoft Security Blog
J
Java Code Geeks
罗磊的独立博客
H
Hackread – Cybersecurity News, Data Breaches, AI and More
量子位
P
Proofpoint News Feed
博客园 - 【当耐特】
MongoDB | Blog
MongoDB | Blog
L
LangChain Blog
F
Fortinet All Blogs
C
Check Point Blog
博客园_首页
I
InfoQ
Jina AI
Jina AI
Blog — PlanetScale
Blog — PlanetScale
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
酷 壳 – CoolShell
酷 壳 – CoolShell
Engineering at Meta
Engineering at Meta
美团技术团队
Vercel News
Vercel News
Apple Machine Learning Research
Apple Machine Learning Research

陈少文的网站

巨变与机遇的未来十年 Kubernetes 平台管理软件压力测试方案 使用镜像部署 Hexo 静态页面 终于等到你 - GitHub 镜像仓库服务(ghcr.io) 一起来学 Go --(6)Interface 一起来学 Go --(5)Goroutine 和 Channel 什么是函数式编程 如何在 Kubernetes 集群集成 Kata 柯里化与偏函数 使用 PyGithub 自动创建 Label 软件产品是团队能力的输出 Helm 2 、Helm 3 比较 IoT 变现 Kubernetes 中的 DNS 服务 国内的 Helm 镜像源 Harbor 使用自签证书支持 Https 访问 DevOps 工具链之 Prow 如何使用 kfctl 安装 Kubeflow VS Code 无法下载 Go 插件的工具包 工程师更应具有服务精神 你不知道的 Docker 使用技巧 使用 Docker 运行 Tensorflow 论中国 什么是左移 如何清空 Git 仓库全部历史记录 一禅小和尚 有风吹过厨房 时间的玫瑰 如何在 CentOS 安装 GPU 驱动 开发 Tips(19)
Vue 中使用 axios
微信公众号 · 2018-06-25 · via 陈少文的网站

1. axios 安装

使用 npm 安装

1
npm install axios --save

全局注册有两种方法:

  1. 绑定到原型上
1
2
import axios from "axios";
Vue.prototype.axios = axios;

这种方法,每个 Vue 对象都会新增一个 axios 对象。

1
2
3
this.axios.post(apiUrl).then((res) => {
  //do something
});
  1. 挂载到 windows 对象上

在 DOM 的任意地方,都能使用 axios 函数。

1
2
import axios from "axios";
window.axios = axios;
1
2
3
axios.post(apiUrl).then((res) => {
  //do something
});

2. axios 配置

为了配合 Django 的 CSRF 校验,需要在 axios 中进行配置。

1
2
3
4
var axiosDefaults = require("axios/lib/defaults");
axiosDefaults.xsrfCookieName = "csrftoken";
axiosDefaults.xsrfHeaderName = "X-CSRFToken";
axiosDefaults.withCredentials = true;

3. axios 拦截器

拦截器可以对请求做一些公共的处理,比如异常、返回数据的格式。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
axios.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    if (error.response) {
      switch (error.response.status) {
        case 500:
          // do something
          break;
        case 402:
          // do something
          break;
      }
    }
    return Promise.reject(error.response.data); // 返回接口返回的错误信息
  },
);

4. axios 传参

4.1 get 请求

1
2
3
4
5
6
let params = {
  key1: "value1",
  key2: "value2",
};
axios.get(apiUrl, { params });
//数据编码形式: /?key1=value1&key2=value2

4.2 POST 请求 x-www-form-urlencoded

axios 默认将 javascript 对象序列化为 JSON 。以 application/x-www-form-urlencoded 格式发送数据。

1
2
3
4
5
let params = new URLSearchParams();
params.append("key1", "value1");
params.append("key2", "value2");
axios.post(apiUrl, params);
//数据编码形式:key1=value1&key2=value2
1
2
3
4
5
6
7
let qs = require("qs");
let params = {
  key1: "value1",
  key2: "value2",
};
axios.post(apiUrl, qs.stringify(params));
//数据编码形式:key1=value1&key2=value2
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import qs from "qs";
let data = {
  key1: "value1",
  key2: "value2",
};
let options = {
  method: "POST",
  headers: { "content-type": "application/x-www-form-urlencoded" },
  data: qs.stringify(data),
  url: apiUrl,
};
axios(options);
// 数据编码形式: key1=value1&key2=value2

4.3 Form data

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
axios.post(
  apiUrl,
  {
    key1: "value1",
    key2: "value2",
  },
  {
    headers: {
      "Content-Type": "multipart/form-data",
    },
  },
);

4.4 request payload

1
2
3
4
let formData = new FormData();
formData.append("key1", "value1");
formData.append("key2", "value2");
axios.post(apiUrl, formData);

5. Django 后台不能区分 ajax 和非 ajax

查看源码 django/http/request.py 文件可以看到,Django 是通过请求头部的标识来区分是否为 Ajax 请求。

1
2
def is_ajax(self):
	return self.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'

axios 处理办法

1
2
3
axiosDefaults.headers.common = {
  "X-Requested-With": "XMLHttpRequest",
};

6. 参考