注意:如果后端是 application/x-www-form-urlencoded 前端必须将传递的json数据转为form data格式。
(1)安装依赖 (项目cmd终端下运行)
npm install axios
npm install qs -S //转换格式用的
(2)在vue项目的main.js文件中引入axios
import axios from 'axios'
import qs from "qs"
(3)Vue·Get请求
//引入 import axios from ‘axios’
//1】地址带参数
axios.get('http://www/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
//2】独立参数
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});或POST请求
//POST请求
axios.post('http://www', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});//headers:{‘Content-Type’: ‘application/x-www-form-urlencoded’}, //请求头
POST请求 完整例子 vue3
import axios from "axios";
import qs from "qs"; //必须
function GetPOST() { // 请求打印
axios({
url: 'http://www',
method: 'post',
transformRequest: [function(data) {
// 对 data 进行任意转换处理
return qs.stringify(data)
}],
headers: {
'content-Type': 'application/x-www-form-urlencoded'
},
data: {
name: 'xxx',
text: 'xxx'
}
})
}配置跨域:
//项目下 vue.config.js 文件 最后面增加
module.exports = { //node.js 语法
devServer: {
// host: '0.0.0.0',
// port: 80,
// open: true,
proxy: {
'api': { //识别api
target: 'http://xxx.xxx.xx', //代理的服务器地址涵端口
changeOrigin: true, //是否跨域
ws: true, //是否代理 websockets
//secure: false, //是否https接口
pathRewrite: { //过滤api字母
'/api': '' //替换字母
}
}
}
}
}