api2.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // api.js
  2. const API_BASE_URL = 'https://pntst.somnisix.top';
  3. // 封装 wx.request 为 Promise 形式
  4. function request(url, method = 'GET', data = {}, headers = {}) {
  5. return new Promise((resolve, reject) => {
  6. wx.request({
  7. url,
  8. method,
  9. data,
  10. header: headers,
  11. success(res) {
  12. if (res.statusCode >= 200 && res.statusCode < 300) {
  13. resolve(res.data);
  14. } else {
  15. reject(new Error(`HTTP error! status: ${res.statusCode}`));
  16. }
  17. },
  18. fail(err) {
  19. reject(new Error('Network error'));
  20. },
  21. });
  22. });
  23. }
  24. const apiClient = {
  25. get: async (endpoint, { params = {}, headers = {} } = {}) => {
  26. let url = `${API_BASE_URL}/${endpoint}`;
  27. // 手动拼接 query 参数
  28. const queryString = Object.keys(params).length > 0
  29. ? '?' + Object.entries(params)
  30. .map(([key, value]) =>
  31. `${encodeURIComponent(key)}=${encodeURIComponent(value)}`
  32. )
  33. .join('&')
  34. : '';
  35. url += queryString;
  36. return await request(url, 'GET', {}, headers);
  37. },
  38. post: async (endpoint, { body = {}, headers = {} } = {}) => {
  39. const url = `${API_BASE_URL}/${endpoint}`;
  40. return await request(url, 'POST', body, headers);
  41. },
  42. // 特定接口封装
  43. getToken: async ({ body = {}, headers = {} } = {}) => {
  44. return await apiClient.post('api/token', { body, headers });
  45. },
  46. print: async ({ body = {}, headers = {} } = {}) => {
  47. return await apiClient.post('api/print/long', { body, headers });
  48. },
  49. };
  50. export default apiClient;