etherreq 1.0.1-0.5 → 1.0.1-0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/src/request.js +24 -8
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "etherreq",
3
- "version": "1.0.10.5",
3
+ "version": "1.0.10.7",
4
4
  "description": "A lightweight custom HTTP request library.",
5
5
  "main": "src/index.js",
6
6
  "types": "src/types/etherreq.d.ts",
package/src/request.js CHANGED
@@ -1,26 +1,36 @@
1
1
  // src/request.js
2
2
  import { create } from './myaxios';
3
3
 
4
+ // 创建一个带有默认配置的请求实例
4
5
  const instance = create({
5
- baseURL: 'https://api.example.com',
6
+ baseURL: 'https://api.example.com', // 默认基础 URL
6
7
  });
7
8
 
8
- // 请求拦截器 - 自动注入 token
9
+ // 请求拦截器:自动注入 token Content-Type
9
10
  instance.interceptors.request.use((config) => {
10
11
  const token = localStorage.getItem('token');
12
+
13
+ // 构建最终 headers
14
+ const headers = {
15
+ ...(config.headers || {}), // 用户自定义 headers
16
+ Authorization: token ? `Bearer ${token}` : undefined,
17
+ };
18
+
19
+ // 如果是 POST/PUT 等非 GET 请求,并且没有指定 Content-Type,则默认为 application/json
20
+ if (config.method !== 'GET' && !headers['Content-Type']) {
21
+ headers['Content-Type'] = 'application/json';
22
+ }
23
+
11
24
  return {
12
25
  ...config,
13
- headers: {
14
- ...(config.headers || {}),
15
- Authorization: token ? `Bearer ${token}` : undefined,
16
- },
26
+ headers,
17
27
  };
18
28
  });
19
29
 
20
- // 响应拦截器 - 返回 data
30
+ // 响应拦截器:自动提取 response.data
21
31
  instance.interceptors.response.use(
22
32
  (response) => {
23
- return response.data; // 自动提取 data
33
+ return response.data; // 返回 data 字段作为结果
24
34
  },
25
35
  (error) => {
26
36
  console.error('请求异常:', error);
@@ -28,9 +38,15 @@ instance.interceptors.response.use(
28
38
  }
29
39
  );
30
40
 
41
+ /**
42
+ * 封装 request 函数,支持 baseURl 拼接等逻辑
43
+ * @param {string} url - 请求路径
44
+ * @param {Object} options - 请求配置
45
+ */
31
46
  export const request = (url, options = {}) => {
32
47
  const baseURL = options.baseURL || 'https://api.example.com';
33
48
  const finalURL = new URL(url, baseURL).toString();
49
+
34
50
  return instance({
35
51
  ...options,
36
52
  url: finalURL,