| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- // api.js
- const API_BASE_URL = 'https://pntst.somnisix.top';
- // 封装 wx.request 为 Promise 形式
- function request(url, method = 'GET', data = {}, headers = {}) {
- return new Promise((resolve, reject) => {
- wx.request({
- url,
- method,
- data,
- header: headers,
- success(res) {
- if (res.statusCode >= 200 && res.statusCode < 300) {
- resolve(res.data);
- } else {
- reject(new Error(`HTTP error! status: ${res.statusCode}`));
- }
- },
- fail(err) {
- reject(new Error('Network error'));
- },
- });
- });
- }
- const apiClient = {
- get: async (endpoint, { params = {}, headers = {} } = {}) => {
- let url = `${API_BASE_URL}/${endpoint}`;
- // 手动拼接 query 参数
- const queryString = Object.keys(params).length > 0
- ? '?' + Object.entries(params)
- .map(([key, value]) =>
- `${encodeURIComponent(key)}=${encodeURIComponent(value)}`
- )
- .join('&')
- : '';
- url += queryString;
- return await request(url, 'GET', {}, headers);
- },
- post: async (endpoint, { body = {}, headers = {} } = {}) => {
- const url = `${API_BASE_URL}/${endpoint}`;
- return await request(url, 'POST', body, headers);
- },
- // 特定接口封装
- getToken: async ({ body = {}, headers = {} } = {}) => {
- return await apiClient.post('api/token', { body, headers });
- },
- print: async ({ body = {}, headers = {} } = {}) => {
- return await apiClient.post('api/print/long', { body, headers });
- },
- };
- export default apiClient;
|