server.tsx 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import axios from "axios";
  2. let baseURL: string;
  3. if (process.env.NODE_ENV === "production") {
  4. baseURL = "";
  5. } else {
  6. baseURL = process.env.NEXT_PUBLIC_DEV_BASE_URL as string;
  7. }
  8. // 拦截器
  9. axios.interceptors.response.use(
  10. (response) => {
  11. return response;
  12. },
  13. (error) => {
  14. return Promise.reject(error);
  15. }
  16. );
  17. axios.interceptors.request.use(
  18. (config) => {
  19. console.log(config);
  20. config.headers["Accept"] = "application/json";
  21. config.baseURL = baseURL;
  22. // config.timeout = 10000;
  23. return config;
  24. },
  25. (error) => {
  26. return Promise.reject(error);
  27. }
  28. );
  29. export function requests<T>(
  30. url: string,
  31. option: {
  32. method: "post" | "get" | "put" | "delete";
  33. params?: { [key: string]: any };
  34. data?: { [key: string]: any };
  35. headers?: { [key: string]: any };
  36. requestType?: "json" | "form";
  37. timeout?: number;
  38. }
  39. ) {
  40. if (!option.requestType) {
  41. option.requestType = "json";
  42. }
  43. return new Promise<T>((resolve, reject) => {
  44. const Content_Type =
  45. option.requestType == "json"
  46. ? "application/json;charset=UTF-8"
  47. : "application/x-www-form-urlencoded;charset=UTF-8";
  48. axios<T>({
  49. timeout: option.timeout,
  50. url: baseURL + url,
  51. method: option.method,
  52. params: option.params,
  53. data: option.data,
  54. headers: {
  55. "Content-Type": Content_Type,
  56. ...option.headers,
  57. },
  58. })
  59. .then((res) => {
  60. resolve(res.data);
  61. })
  62. .catch((err) => {
  63. reject(err);
  64. });
  65. });
  66. }
  67. export default requests;