参考资料
一,axios封装
事前准备
禁止eslint检查
在vue.config.js中 添加 lintOnSave: false
如下图所示
如果没有安装axios:
npm install axios
使用json-server
使用json-server以测试获取后端的数据
- 安装:
npm install -g json-server
- 创建db.json
{
"posts": [
{
"id": 1,
"title": "json-server",
"author": "typicode"
}
],
"comments": [
{
"id": 1,
"body": "some comment",
"postId": 1
}
],
"profile": {
"name": "typicode"
}
}
- 启动json-server
json-server –watch db.json
json-server –watch db.json -d 2000 #延时两秒在返回结果
编写 plugins/axios
使用拦截器: 拦截器在vue2 vue3中都可以使用
使用拦截器这样写
import axios from "axios";
// Add a request interceptor
axios.interceptors.request.use(
function (config) {
// Do something before request is sent
return config;
},
function (error) {
return Promise.reject(error);
}
);
// Add a response interceptor
axios.interceptors.response.use(
function (response) {
console.log("响应", response);
// Any status code that lie within the range of 2xx cause this function to trigger
// Do something with response data
return response;
},
function (error) {
// Any status code that false outside the range of 2xx cause this function to trigger
// Do something with response error
return Promise.reject(error);
}
);
在main.js中只需添加一行
import "./plugins/axios1"
在组件中使用axios
// 1) 使用axios({ })
axios({
url: "http://localhost:3000/posts",
data: "",
methods: "GET",
}).then((res)=>{
console.log(res);
})
// 2) 使用axios.xxx()
axios.get("/api/depts").then((res)=>{
console.log(res)
});
在vue3中使用 myRequest
import qs from "qs";
import axios from "axios";
const myRequest = (options) => {
return new Promise((resolve, reject) => {
let url = options.url;
let method = options.method || "GET";
let data = options.data || {};
if (method === "GET") {
// 将data对象转化成字符串
data = qs.stringify(data);
}
axios({
method,
url,
data,
})
.then((res) => {
console.log("响应 res.data = ")
console.log(res.data)
// 请求错误 res.data为空,或者res.data.status为空
if (!(res.data && res.data.status)) {
resolve(res);
} else {
// 其他情况 正确情况下
resolve(res);
}
})
.catch(() => {
resolve({
data: {
msg: "请求错误",
status: -1,
},
});
});
});
};
export default myRequest;
在main.js 中使用 globalProperties.$myRequest
import App from './App.vue'
import { createApp } from 'vue'
import myRequest from "./plugins/axios";
const app = createApp(App)
app.config.globalProperties.$myRequest = myRequest;
在组件中使用
this.$myRequest({
url: "http://localhost:3000/posts",
data: {},
methods: "GET",
}).then((res) => {
console.log(res.data)
})
在vue2中使用 _axios
在使用 axios
import axios from 'axios';
let _axios=axios.create({
// 这里写入配置
baseURL: 'http://localhost:8080/', // 设置所有 Axios 请求的基本 URL
timeout: 10*1000 // 设置最长时间,单位毫秒
})
export default _axios
在main.js中 引入
import Vue from 'vue'
import App from './App.vue'
import _axios from './plugin/axios'
Vue.prototype.$axios=_axios //给全局Vue实例对象添加axios属性
在组件中使用
this.$axios.get('http://localhost:3000/posts').then(function (resp) {
console.log(resp.data)
})
二,在vue中向后端传递文件
前端信息
页面信息:
<div>
<input type="file" name="" ref="file">
<button @click="click">上传</button>
</div>
后台信息:
methods: {
click(){
// 数据这里我使用了 new FormData
var forms = new FormData()
var configs = { // 上传文件 请求头要设置成下面这样
headers:{'Content-Type':'multipart/form-data'}
};
forms.append('file',this.$refs.file.files[0]);// 获取上传图片信息
//forms.append('type','img'); // 添加一些图片的自定义信息
//forms.append('name','touxiang.jpg');
axios.post('/api/upload',forms ,configs).then(res=>{
console.log("res = ")
console.log(res.data.data)
})
}
},
后端信息:
common
返回信息
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result<T> {
private Integer code;
private String msg;
private T data;
private static final Integer code_ok = 1;
private static final String msg_success = "操作成功";
private static final String msg_error = "操作失败";
// 增删改 成功
public static <T> Result<T> success(){
return new Result<>(1,"success",null);
}
// 查询 成功
public static <T> Result<T> success(Integer code,T data){
return new Result<>(code,"success",data);
}
// 四项全部失败
public static <T> Result<T> error(Integer code,String msg,T data){
return new Result<>(code,msg,data);
}
}
controller
通过时间定义文件名:
Date date = new Date();
long t = date.getTime();
// 创建日期格式化对象,在获取格式化对象时可以指定风格
DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss"); //时间格式
String str = df.format(date); // 获得从 1977 某个时间的到此的毫秒数
后端接受文件
@Slf4j
@RestController
public class UploadController {
@PostMapping("/upload")
public Result uploadFile(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return Result.error(0, "文件是空的", null);
}
log.info("文件上传 {}", file);
try {
// 获得文件原始名称
String originalFilename = file.getOriginalFilename();
System.out.println("originalFilename = " + originalFilename);
// 设置日期
Date date = new Date();
// 获得毫秒数
long t = date.getTime();
// 创建日期格式化对象,在获取格式化对象时可以指定风格
DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String str = df.format(date);
str += Long.toString(t);
str += "-";
str += originalFilename;
System.out.println(str);
// 将文件储存在这个位置,并重新命名
file.transferTo(new File("C:\\Users\\yang99977\\Pictures\\Saved Pictures\\img\\" + str));
return Result.success();
} catch (Exception e) {
log.info("出错了");
return Result.error(0, "文件上传失败", null);
}
}
}