You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
93 lines
1.9 KiB
93 lines
1.9 KiB
//服务端地址
|
|
|
|
const server="http://localhost:8080"
|
|
|
|
const prefix={
|
|
user:"/api/user"
|
|
}
|
|
//服务器接口地址
|
|
export const API={
|
|
account:{
|
|
register:prefix.user+"/register",
|
|
login:prefix.user+"/login"
|
|
}
|
|
}
|
|
|
|
export enum Method {
|
|
PUT="PUT",
|
|
POST="POST",
|
|
GET="GET"
|
|
}
|
|
|
|
export enum Result {
|
|
OK,
|
|
FAIL
|
|
}
|
|
|
|
|
|
/**
|
|
* 响应数据
|
|
*/
|
|
export abstract class JSONResponse<Q> {
|
|
result?:Result
|
|
customResult?:Q
|
|
}
|
|
|
|
/**
|
|
* 数据类型转换
|
|
*/
|
|
export abstract class TransformData<Q,T extends JSONResponse<Q>> {
|
|
protected target: T
|
|
|
|
constructor() {
|
|
this.target = this.newObject();
|
|
}
|
|
|
|
protected abstract newObject(): T
|
|
|
|
public transform(data:any){
|
|
this.transformResult(data)
|
|
this.transformBody(data)
|
|
return this.target
|
|
}
|
|
|
|
protected transformBody(data:any){
|
|
|
|
}
|
|
|
|
private transformResult(data:any){
|
|
if("result" in data ) {
|
|
this.target.result = data.result
|
|
}
|
|
if("customResult" in data){
|
|
this.target.customResult = data.customResult
|
|
}
|
|
}
|
|
}
|
|
|
|
//发送请求
|
|
export function request<Q,E extends JSONResponse<Q>,T extends TransformData<Q,E>>(api:string,method:Method,formParams: {[propName:string]: string | Blob},transformFun:Function,callback:Function) {
|
|
let formData=new FormData()
|
|
for(let formParam in formParams){
|
|
formData.append(formParam,formParams[formParam])
|
|
}
|
|
fetch(server+api,{
|
|
method:method,
|
|
body:formData
|
|
})
|
|
.then(
|
|
response=>{if(response.status===200){
|
|
return response.json()
|
|
}else{
|
|
throw new Error("遇到无法处理的错误,请联系管理员")
|
|
|
|
}}
|
|
)
|
|
.catch(
|
|
error =>console.error('Error:', error)
|
|
)
|
|
.then((response:JSONResponse<Q>)=>{
|
|
let transform:T=transformFun()
|
|
callback(transform.transform(response))
|
|
})
|
|
}
|
|
|