基于vue3.0和element-plus的组件库
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.

205 lines
4.8 KiB

# Axios2 (Second HTTP Client Variant)
> Enhanced axios wrapper with router integration and success response handling.
## File
`plugs/http/axios2.ts`
---
## Overview
Second iteration of HTTP client. Adds router integration for session timeout navigation and response success checking with automatic message display.
---
## Key Differences from Axios
| Feature | Axios | Axios2 |
|---------|-------|--------|
| Router integration | None | `registerRouter()` |
| Response handling | Raw data | Checks `response.success` |
| Session timeout handling | None | Redirects to `/login` |
| String data handling | None | Sets `Content-Type: text/plain` |
| Delete method | Custom object | Custom object (same as axios) |
---
## Axios Instance Configuration
```typescript
const config = {
baseURL: process.env.VUE_APP_BASE_URL ? "/api" : "",
timeout: 60 * 1000,
withCredentials: true,
};
export const _axios = axios.create(config);
```
---
## Router Registration
```typescript
let router;
export const registerRouter = (routerP) => {
router = routerP;
};
```
---
## Request Interceptor
Located at `plugs/http/axios2.ts` lines 27-48:
```typescript
_axios.interceptors.request.use(
function (config) {
const time = new Date().getTime().toString();
const params = config.params;
if (params) {
delEmpty(params);
params.t = time;
}
const data = config.data;
if (data != null && typeof data === "object") {
delEmpty(data);
data.t = time;
}
if (data != null && typeof data === "string" && config?.headers) {
config.headers["Content-Type"] = "text/plain;charset=UTF-8";
}
return config;
},
function (error) {
return Promise.reject(error);
}
);
```
### Additional Behavior vs Axios
- **String data**: Sets `Content-Type: text/plain;charset=UTF-8` for string payloads
---
## Response Handling
Located at `plugs/http/axios2.ts` lines 149-181:
```typescript
function handResponse(response, resolve, noMsg, noLoading) {
if (!noLoading) {
close();
}
if (response.success) {
if (response.message) {
if (!noMsg) {
showMessage("success", response.message);
}
resolve(true);
} else if (response.data) {
resolve(response.data);
} else {
resolve(true);
}
} else {
if (response.message == "session timeout") {
router?.push("/login");
response.message = t("http.unLogin");
}
if (response.message == "no permission") {
response.message = t("http.unPermission");
}
if (response.message?.indexOf("no permission for ") == 0) {
response.message = t("http.noPermission");
}
if (!noMsg && response.message) {
showMessage("error", response.message);
}
response.error && console.log(response.error);
resolve(false);
}
}
```
### Response Success Flow
1. Check `response.success === true`
2. If `response.message` exists, show success message and resolve `true`
3. If `response.data` exists, resolve with `response.data`
4. Otherwise resolve `true`
### Error Response Flow
1. Check `response.message` for:
- `"session timeout"` -> Navigate to `/login`, show translated message
- `"no permission"` -> Translate to `t("http.unPermission")`
- `"no permission for ..."` -> Translate to `t("http.noPermission")`
2. Show error message if not `noMsg`
3. Resolve `false` (not reject)
---
## delEmpty Function
Located at `plugs/http/axios2.ts` lines 50-61:
```typescript
function delEmpty(data) {
if (data) {
for (const item in data) {
if (data.hasOwnProperty(item)) {
const val = data[item];
if ((val == null || val == "null" || val == "") && val !== 0) {
delete data[item];
}
}
}
}
}
```
**Note**: Identical to axios.ts version.
---
## Export Methods
Same signature as Axios:
| Method | Signature | Purpose |
|--------|-----------|---------|
| `post` | `(url, data?, noMsg?, noLoading?)` | POST request |
| `get` | `(url, data?, noMsg?, noLoading?)` | GET request |
| `put` | `(url, data?, noMsg?, noLoading?)` | PUT request |
| `delate` | `(url, data?, noMsg?, noLoading?)` | DELETE request |
| `upload` | `(file, url, data)` | File upload |
| `download` | `(fileName, url, data, callBack?)` | Browser download |
| `registerRouter` | `(routerP)` | Set router for redirects |
---
## Download Behavior
Similar to axios with one difference:
```typescript
const blob = new Blob([response], {
type: "application/vnd.ms-excel", // Axios2: excel type
// Axios: "application/octet-stream"
});
```
---
## Anti-Patterns
1. **`delate` function name** - Should be `delete`
2. **Resolves `false` for errors** - Inconsistent, should reject or have consistent boolean handling
3. **Incomplete success check** - Only checks `response.success`, not other success indicators like axios3