项目描述
上传时间
浏览人数
vue3带参访问接口的6种方式
常见的http请求方式包括:get、post、put、delete等。其中 get、post也是最常见的两种接口类型
(1)get类型接口
格式:请求数参数写在网址后面,用”?”连接,多个参数之间用”&”连接。
场景:get型接口用于获取信息,一般情况下请求的数据量较小,返回速度快,不过接口是暴露在外面的,所以会有一定的风险。
(2)post型接口
说明:向指定资源位置提交数据(如提交表单、上传文件)来进行请求,post请求可能会导致新资源的建立。
场景:如注册、上传、发帖等功能,这种请求数据量大,安全性要求高
GET
const http ={
/**
* methods: 请求
* @param url 请求地址
* @param params 请求参数
*/
get(url,params){
const config = {
method: 'get',
url:url
};
if(params) config.params = params;
return request(config)
},
}
//导出
export default http
接口示例1:
方式1 :
export function xxx(){
return http.get('http://xxxx.com/xxxx?Id=1',{})
}
动态参数:
export function xxx(参数){
return http.get('http://xxxx.com/xxxx?Id='+参数)
}
方式2 :
export function xxx({"Id":1}){
return http.get('http://xxxx.com/xxxx',{"Id":1})
}
动态参数:
export function xxx(参数){
return http.get('http://xxxx.com/xxxx,参数)
}
接口示例2:
方式3 :
export function xxx(){
return http.get('http://xxxx.com/xxxx/1,{})
}
动态参数:
export function xxx(参数){
return http.get('http://xxxx.com/xxxx/'+参数)
}
POST
1. Post普通方式 :
添加个人信息接口示例:
示例参数: {"id" : "" , "name" : ""}
const http ={
/**
* methods: 请求
* @param url 请求地址
* @param params 请求参数
*/
post(url,params){
const config = {
method: 'post',
url:url
};
if(params) config.data = params;
return request(config)
},
}
//导出
export default http
export function xxx( ){
return http.post('http://xxxx.com/addInfo', {"id":1005, "name":"小李"} )
}
2. Post携带文件的形式:
接口示例:
http://xxxx.com/addInfo
示例参数: {"id":"" , "name":"", pic:""} 参数要放在FormData里面
const http ={
/**
* methods: 请求
* @param url 请求地址
* @param params 请求参数
*/
postFile(url,paramsFormData){
const config = {
method: 'post',
url:url,
headers: {
'Content-Type': 'multipart/form-data'
},
};
if(paramsFormData) config.data = paramsFormData;
return request(config)
},
}
//导出
export default http
let formData = new FormData();
formData .append("id":1005);
formData .append( "name":"小李");
formData .append(pic:"图片文件");
export function xxx( formData ){
return http.postFile('http://xxxx.com/addInfo', formData )
}
3. Post之Raw传值:
接口示例:
http://xxxx.com/addInfo
示例参数: {"id":"" , "name":"", age:""}
const http ={
/**
* methods: 请求
* @param url 请求地址
* @param params 请求参数
*/
raw(url,params){
const config = {
method: 'post',
url:url,
headers: {
'Content-Type': 'application/json'
},
};
if(params) config.data = JSON.stringify(params);
return request(config)
},
}
//导出
export default http
let params = {"id":1, "name":"xxx", "age":18};
export function xxx( params ){
return http.raw('http://xxxx.com/addInfo', params )
}