vue简易Http请求
程序员文章站
2022-10-25 13:36:43
####http.js 工具类import axios from 'axios';axios.defaults.baseURL = "http://localhost:8090/";axios.defaults.responseType = 'json';axios.defaults.timeout = 200000;//getconst get = (url, params) => { return axios({ method: 'get',...
####http.js 工具类
路由的细节就不说了,直接看代码吧
import axios from 'axios';
axios.defaults.baseURL = "http://localhost:8090/";
axios.defaults.responseType = 'json';
axios.defaults.timeout = 200000;
//get
const get = (url, params) => {
return axios({
method: 'get',
withCredentials: true,
url,
headers: {
'Content-Type': 'application/json;charset=UTF-8',
timestamp: getNow(new Date()),
apiCode: url,
apiVersion: '1.0.0',
},
params,
data: undefined,
});
};
//post
const post = (url, data) => {
console.log('url:' + url);
console.log('data:' + JSON.stringify(data));
if (!data) {
data = {};
}
data = JSON.stringify(data);
return axios({
method: 'post',
withCredentials: true,
url,
responseType: 'text',
headers: {
'Content-Type': 'application/json;charset=UTF-8',
timestamp: getNow(new Date()),
apiCode: url,
apiVersion: '1.0.0',
},
transformResponse: [
function(data) {
return JSON.parse(data);
},
],
pararms: undefined,
data: data || {},
});
};
const getNow = now => {
return (
now.getFullYear() +
fillDate(now.getMonth()) +
fillDate(now.getDate()) +
fillDate(now.getHours()) +
fillDate(now.getMinutes()) +
fillDate(now.getSeconds())
);
};
const fillDate = str => {
if (('' + str).length == 1) {
str = '0' + str;
}
return ('' + str).length == 1 ? '0' + str : str;
};
export default { get, post };
#####调用:
<template>
<button @click="testClick">test</button>
</template>
<script>
export default {
name: 'HelloWorld',
props: {
// msg: String
},
data() {
return {
test: ''
}
},
methods: {
testClick() {
//调用后台接口
this.$http
.get('/user/queryUser')
.then(res => {
console.log(res);
})
.catch(function() {
});
}
}
}
</script>
<style scoped>
</style>
结果:
本文地址:https://blog.csdn.net/qq_42919520/article/details/107161918
推荐阅读
-
详解vue-cli 构建项目 vue-cli请求后台接口 vue-cli使用axios、sass、swiper
-
.NET Http请求
-
Linux下模拟http的get/post请求(curl or wget)详解
-
python使用urllib2提交http post请求的方法
-
python通过get,post方式发送http请求和接收http响应的方法
-
Postman请求后台报错:Invalid character found in method name. HTTP method names must be tokens
-
vue项目使用axios发送请求让ajax请求头部携带cookie的方法
-
vue2中使用less简易教程
-
vue + socket.io实现一个简易聊天室示例代码
-
浅谈Vue下使用百度地图的简易方法