Front-end Dev Engineer

0%

Vue项目中使用axios进行跨域请求

在练习前后端的项目中,前端通过Vue框架实现,后端通过NodeJs实现,在处理前端的http请求中使用了Axios模块,同时还进行了跨域的配置,具体查看文档内容;

Vue项目中使用axios进行跨域请求

1. Vue项目中下载并安装 axios 模块

1
2
3
4
# 下载axios包
npm install axios
# 或者使用yarn下载
yarn add axios

2. 封装http请求方法

新建一个js的文件(service.js),用于封装 axios 方法,并将接口暴露出去;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import axios from 'axios'
import qs from 'qs'
export default {
post (url, data) {
return axios({
method: 'post',
baseURL: 'http://localhost:8000/',
url,
data: qs.stringify(data),
timeout: 5000,
headers: {
'X-Requested-With': 'XMLHttpRequest',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
})
},
get (url, params) {
return axios({
method: 'get',
baseURL: 'http://localhost:8000/',
url,
params,
timeout: 5000,
headers: {
'X-Requested-With': 'XMLHttpRequest'
}
})
}
}

3. 将 axios 对象挂载到Vue原型链上

1
2
3
4
// 引入刚刚的service.js文件
import axios from './service.js'
// 挂载属性到Vue的原型链上
Vue.prototype.$http = axios

可以通过 this.$http.get() 或者 this.$http.post () 获取进行数据接口请求,然后再通过promise进行处理返回的数据;

(补充)4. 跨域请求对于后端项目的设置

在练习项目中,后端服务器是使用 nodejs 搭建的,在根目录下的 app.js 中增加对于前端项目的跨域请求设置,设置如下:

1
2
3
4
5
6
7
8
9
10
// 设置跨域接受到的所有请求头的类型
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By",' 3.2.1');
res.header("Content-Type", "application/json;charset=utf-8");
res.header("Cache-Control","no-store");
next();
});
-------------    本文结束  感谢您的阅读    -------------

赞赏一下吧~ 还可以关注公众号订阅最新内容