SpringBoot + VUE3 +deepseek实现的简朴的AI对话页面(无广告,不会员)

[复制链接]
发表于 2025-7-9 00:24:49 | 显示全部楼层 |阅读模式
主要使用SpringBoot + VUE3 +deepseek实现的简朴的AI对话页面

页面有点简朴


主要写了三种方式

使用前在API_KEY更换成自己的key,模子可以使用V3大概R1

1.单纯的多轮对话
  1. import okhttp3.*;
  2. import java.io.IOException;
  3. import java.util.Objects;
  4. import java.util.concurrent.TimeUnit;
  5. public class DeepSeekOkHttpClient implements DeepSeekClient {
  6.     private static final String API_URL = "https://api.deepseek.com/v1/chat/completions";
  7.     private static final String API_KEY = "sk-xxx"; // 请务必妥善保管API_KEY
  8.     private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
  9.     private final OkHttpClient client;
  10.     // 设置超时常量
  11.     private static final int CONNECT_TIMEOUT = 10; // 连接超时(秒)
  12.     private static final int READ_TIMEOUT = 130;    // 读取超时(秒)
  13.     private static final int WRITE_TIMEOUT = 30;   // 写入超时(秒)
  14.     public DeepSeekOkHttpClient() {
  15.         this.client = new OkHttpClient.Builder()
  16.                 .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS) // 设置连接超时
  17.                 .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)       // 设置读取超时
  18.                 .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)     // 设置写入超时
  19.                 .build();
  20.     }
  21.     @Override
  22.     public String getChatCompletion(String userMessage) {
  23.         String requestBody = String.format("{"model":"deepseek-chat","messages":[{"role":"user","content":"%s"}]}", userMessage);
  24.         RequestBody body = RequestBody.create(requestBody, JSON);
  25.         Request request = new Request.Builder()
  26.                 .url(API_URL)
  27.                 .addHeader("Authorization", "Bearer " + API_KEY)
  28.                 .post(body)
  29.                 .build();
  30.         try (Response response = client.newCall(request).execute()) {
  31.             if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
  32.             return Objects.requireNonNull(response.body()).string();
  33.         } catch (IOException e) {
  34.             e.printStackTrace();
  35.             return null;
  36.         }
  37.     }
  38. }
复制代码
2.可以指定脚色的对话
在这里指定
  1. messages.put(new JSONObject()
  2.                 .put("role", "system")
  3.                 .put("content", "用精简语言回答问题,但是要回答准确全面!"));
复制代码
完备代码
  1. import okhttp3.*;import org.json.JSONArray;import org.json.JSONObject;import java.io.IOException;import java.util.concurrent.TimeUnit;public class DeepSeekChatWithRole {    private static final String API_URL = "https://api.deepseek.com/v1/chat/completions";    private static final String API_KEY = "sk-xxx"; // 请妥善保管API_KEY    private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");    // 设置超时常量    private static final int CONNECT_TIMEOUT = 10; // 毗连超时(秒)    private static final int READ_TIMEOUT = 130;    // 读取超时(秒)    private static final int WRITE_TIMEOUT = 30;   // 写入超时(秒)    private final OkHttpClient client;    public DeepSeekChatWithRole() {        this.client = new OkHttpClient.Builder()                .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS) // 设置毗连超时                .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)       // 设置读取超时                .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)     // 设置写入超时                .build();    }    public String getChatCompletion(String userMessage) throws IOException {        JSONArray messages = new JSONArray();        messages.put(new JSONObject()
  2.                 .put("role", "system")
  3.                 .put("content", "用精简语言回答问题,但是要回答准确全面!"));
  4.         messages.put(new JSONObject()                .put("role", "user")                .put("content", userMessage));        JSONObject requestBody = new JSONObject()                .put("model", "deepseek-reasoner")                .put("messages", messages)                .put("temperature", 0.7);  // 控制回答的随机性(0-1)        RequestBody body = RequestBody.create(requestBody.toString(), JSON);        Request request = new Request.Builder()                .url(API_URL)                .addHeader("Authorization", "Bearer " + API_KEY)                .post(body)                .build();        try (Response response = client.newCall(request).execute()) {            if (!response.isSuccessful()) {                throw new IOException("API 哀求失败: " + response.code() + " - " + response.message());            }            return response.body().string();        }    }    public static void main(String[] args) {        DeepSeekChatWithRole chatClient = new DeepSeekChatWithRole();        try {            String response = chatClient.getChatCompletion("Java 的 HashMap 和 LinkedHashMap 有什么区别?");            System.out.println("AI 回答: " + response);        } catch (IOException e) {            e.printStackTrace();        }    }}
复制代码
3.带上下文关联,指定脚色回复
这里主要思路是:用redis存对话的汗青,然后每次会话会获取天生一个随机的不重复的key,用这个key存这次会话的汗青,在当前会话,每次举行对话时,都会传入key 作为获取汗青的参数,以达到上下文关联的目的
  1. import okhttp3.*;
  2. import org.json.JSONArray;
  3. import org.json.JSONObject;
  4. import redis.clients.jedis.Jedis;
  5. import java.io.IOException;
  6. import java.security.SecureRandom;
  7. import java.util.ArrayList;
  8. import java.util.List;
  9. import java.util.concurrent.TimeUnit;
  10. public class ChatRedisContext {
  11.     private static final String API_URL = "https://api.deepseek.com/v1/chat/completions";
  12.     private static final String API_KEY = "sk-xxx";
  13.     private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
  14.     // 超时设置
  15.     private static final int CONNECT_TIMEOUT = 10;
  16.     private static final int READ_TIMEOUT = 130;
  17.     private static final int WRITE_TIMEOUT = 30;
  18.     private final OkHttpClient client;
  19.     private final String redisHost = "127.0.0.1"; // Redis 服务器地址
  20.     private final int redisPort = 6379; // Redis 服务器端口
  21.     private static final String ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  22.     private static final SecureRandom random = new SecureRandom();
  23.     public ChatRedisContext() {
  24.         this.client = new OkHttpClient.Builder()
  25.                 .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
  26.                 .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
  27.                 .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
  28.                 .build();
  29.     }
  30.     private static class Message {
  31.         String role;
  32.         String content;
  33.         public Message(String role, String content) {
  34.             this.role = role;
  35.             this.content = content;
  36.         }
  37.         public JSONObject toJson() {
  38.             return new JSONObject()
  39.                     .put("role", this.role)
  40.                     .put("content", this.content);
  41.         }
  42.     }
  43.     private void saveConversationHistory(String conversationKey, List<Message> history) {
  44.         JSONArray messagesJson = new JSONArray();
  45.         for (Message msg : history) {
  46.             messagesJson.put(msg.toJson());
  47.         }
  48.         try (Jedis jedis = new Jedis(redisHost, redisPort)) {
  49.             // 设置键值并设置过期时间为 12 小时(43200 秒)
  50.             jedis.setex(conversationKey, 43200, messagesJson.toString());
  51.         }
  52.     }
  53.     private List<Message> getConversationHistory(String conversationKey) {
  54.         try (Jedis jedis = new Jedis(redisHost, redisPort)) {
  55.             String historyJson = jedis.get(conversationKey);
  56.             List<Message> history = new ArrayList<>();
  57.             if (historyJson != null) {
  58.                 JSONArray messagesJson = new JSONArray(historyJson);
  59.                 for (int i = 0; i < messagesJson.length(); i++) {
  60.                     JSONObject msgJson = messagesJson.getJSONObject(i);
  61.                     history.add(new Message(msgJson.getString("role"), msgJson.getString("content")));
  62.                 }
  63.             }
  64.             return history;
  65.         }
  66.     }
  67.     public String chat(String conversationKey, String userMessage) throws IOException {
  68.         List<Message> conversationHistory = getConversationHistory(conversationKey);
  69.         if (conversationHistory.isEmpty()) {
  70.             conversationHistory.add(new Message("system", "用精简语言回答问题,但是要回答准确全面!"));
  71.         }
  72.         conversationHistory.add(new Message("user", userMessage));
  73.         JSONArray messages = new JSONArray();
  74.         for (Message msg : conversationHistory) {
  75.             messages.put(msg.toJson());
  76.         }
  77.         JSONObject requestBody = new JSONObject()
  78.                 .put("model", "deepseek-chat")
  79.                 .put("messages", messages)
  80.                 .put("temperature", 0.7);
  81.         RequestBody body = RequestBody.create(requestBody.toString(), JSON);
  82.         Request request = new Request.Builder()
  83.                 .url(API_URL)
  84.                 .addHeader("Authorization", "Bearer " + API_KEY)
  85.                 .post(body)
  86.                 .build();
  87.         try (Response response = client.newCall(request).execute()) {
  88.             if (!response.isSuccessful()) {
  89.                 throw new IOException("API 请求失败: " + response.code() + " - " + response.message());
  90.             }
  91.             String responseBody = response.body().string();
  92.             JSONObject jsonResponse = new JSONObject(responseBody);
  93.             String aiResponse = jsonResponse.getJSONArray("choices")
  94.                     .getJSONObject(0)
  95.                     .getJSONObject("message")
  96.                     .getString("content");
  97.             conversationHistory.add(new Message("assistant", aiResponse));
  98.             saveConversationHistory(conversationKey, conversationHistory);
  99.             return aiResponse;
  100.         }
  101.     }
  102.     public static String generateUniqueKey() {
  103.         long timestamp = System.currentTimeMillis();
  104.         StringBuilder randomString = new StringBuilder();
  105.         for (int i = 0; i < 8; i++) { // 生成8个随机字母
  106.             int index = random.nextInt(ALPHABET.length());
  107.             randomString.append(ALPHABET.charAt(index));
  108.         }
  109.         return timestamp + "_" + randomString.toString();
  110.     }
  111.     public void clearConversation(String conversationKey) {
  112.         try (Jedis jedis = new Jedis(redisHost, redisPort)) {
  113.             if (null != conversationKey && jedis.exists(conversationKey)){
  114.                 jedis.del(conversationKey);
  115.             }
  116.         }
  117.     }
  118.    
  119. }
复制代码
寻常对话我还多写了一个接口方法,其实也不需要的
  1. /**
  2. * <描述>
  3. *
  4. * @author lj
  5. * @date 2025/5/26  9:34
  6. */
  7. public interface DeepSeekClient {
  8.     String getChatCompletion(String userMessage);
  9. }
复制代码
主要的实现类
  1. import com.alibaba.fastjson.JSON;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.zkzm.dpDemo.client.*;
  4. import org.springframework.http.ResponseEntity;
  5. import org.springframework.web.bind.annotation.GetMapping;
  6. import org.springframework.web.bind.annotation.RequestParam;
  7. import org.springframework.web.bind.annotation.RestController;
  8. import java.io.IOException;
  9. import java.util.HashMap;
  10. import java.util.Map;
  11. /**
  12. * <描述>
  13. *
  14. * @author lj
  15. * @date 2025/5/26  9:35
  16. */
  17. @RestController
  18. public class DpController {
  19.     public static void main(String[] args) {
  20.         DeepSeekClient deepSeekClient = new DeepSeekOkHttpClient();
  21.         String userMessage = "你好,你是谁?";
  22.         String response = deepSeekClient.getChatCompletion(userMessage);
  23.         System.out.println("Response: " + response);
  24.     }
  25.     /**
  26.      * 普通多轮对话
  27.      * */
  28.     @GetMapping("getText")
  29.     public ResponseEntity<Map<String, Object>> getText(String message) {
  30.         DeepSeekClient deepSeekClient = new DeepSeekOkHttpClient();
  31.         Map<String, Object> responseMap = new HashMap<>();
  32.         try {
  33.             String result = deepSeekClient.getChatCompletion(message);
  34.             JSONObject nestedJson = JSON.parseObject(result);
  35.             responseMap.put("message", nestedJson);
  36.             responseMap.put("status", "success");
  37.             return ResponseEntity.ok(responseMap);
  38.         } catch (Exception e) {
  39.             responseMap.put("message", "Error: " + e.getMessage());
  40.             responseMap.put("status", "error");
  41.             return ResponseEntity.status(500).body(responseMap);
  42.         }
  43.     }
  44.     /**
  45.      * 带角色对话
  46.      * */
  47.     @GetMapping("getTextWithRole")
  48.     public String getTextWithRole(String message) throws IOException {
  49.         DeepSeekChatWithRole client = new DeepSeekChatWithRole();
  50.         String response = client.getChatCompletion(message);
  51.         return response;
  52.     }
  53.     @GetMapping("getTextWithContext")
  54.     public String getTextWithContext(String message) throws IOException {
  55.         DeepSeekChatWithContext client = new DeepSeekChatWithContext();
  56.         String response = client.chat(message);
  57.         return response;
  58.     }
  59.     /**
  60.      * 基于redis的上下文
  61.      * */
  62.     @GetMapping("getChatRedisContext")
  63.     public String getChatRedisContext(String message,String conversationKey) throws IOException {
  64.         ChatRedisContext chatClient = new ChatRedisContext();
  65.         String response = chatClient.chat(conversationKey, message);
  66.         return response;
  67.     }
  68.     /**
  69.      * 生成redis的key
  70.      * */
  71.     @GetMapping("getKey")
  72.     public String getKey() throws IOException {
  73.         return ChatRedisContext.generateUniqueKey();
  74.     }
  75.     /**
  76.      * 清空redis的key
  77.      * */
  78.     @GetMapping("clearConversation")
  79.     public void clearConversation(String conversationKey) throws IOException {
  80.         ChatRedisContext chatClient = new ChatRedisContext();
  81.         chatClient.clearConversation(conversationKey);
  82.     }
  83. }
复制代码
pom.xml
  1.   <dependency>
  2.             <groupId>com.squareup.okhttp3</groupId>
  3.             <artifactId>okhttp</artifactId>
  4.             <version>4.9.2</version>
  5.         </dependency>
  6.         <dependency>
  7.             <groupId>com.alibaba</groupId>
  8.             <artifactId>fastjson</artifactId>
  9.             <version>1.2.83</version>
  10.         </dependency>
  11.         <!-- https://mvnrepository.com/artifact/org.json/json -->
  12.         <dependency>
  13.             <groupId>org.json</groupId>
  14.             <artifactId>json</artifactId>
  15.             <version>20240303</version>
  16.         </dependency>
  17.         <dependency>
  18.             <groupId>redis.clients</groupId>
  19.             <artifactId>jedis</artifactId>
  20.             <version>4.3.1</version> <!-- 确保使用的是最新版本 -->
  21.         </dependency>
复制代码
接下来是前端代码,主要使用的是第三种方式(基于redis实现上下文)

1.每次页面加载,会默认创建一个会话,即调用获取key的接口
2.每次新增一个会话都会调用获取key的接口,确保每个会话的key是唯一的,达到上下文的目的
3.删除会话,会调用后台删除key的接口,同步删除了redis中的key
完备代码
.vue
  1. <template>
  2.   <div id="app">
  3.     <div class="sidebar">
  4.       <h2>会话列表</h2>
  5.       <ul>
  6.         <li v-for="(session, index) in sessions" :key="index">
  7.           <span @click="loadSession(index)">{{ session.title }}</span>
  8.           <button @click="deleteSession(index)">删除</button>
  9.         </li>
  10.       </ul>
  11.       <button @click="startNewSession" :disabled="sessions.length >= 10">+ 新会话</button>
  12.     </div>
  13.     <div class="chat-container">
  14.       <div class="chat-title">{{ currentSession.title }}</div>
  15.       <div class="messages" ref="messagesContainer">
  16.         <div v-for="(msg, index) in currentSession.messages" :key="index" class="message" :class="msg.role">
  17.           <span class="role">{{ msg.role }}:</span>
  18.           <span class="content">{{ msg.content }}</span>
  19.         </div>
  20.         <div v-if="currentSession.loading" class="message assistant">
  21.           <span class="role">小助手:</span>
  22.           <span class="content">加载中...</span>
  23.         </div>
  24.         <div v-if="currentSession.timeout && !currentSession.loading" class="message assistant">
  25.           <span class="role">小助手:</span>
  26.           <span class="content">请求超时,请稍后再试。</span>
  27.         </div>
  28.       </div>
  29.       <div class="input-container">
  30.         <input v-model="userMessage" @keyup.enter="sendMessage" type="text" placeholder="输入你的消息..." />
  31.         <button @click="sendMessage"
  32.           :disabled="!currentSession.conversationKey || currentSession.loading || currentSession.timeout">发送</button>
  33.       </div>
  34.     </div>
  35.   </div>
  36. </template>
  37. <script>
  38. import { chat, getKey, clearConversation } from '@/api/main';
  39. import { ref, nextTick, onMounted } from 'vue';
  40. export default {
  41.   setup() {
  42.     const userMessage = ref('');
  43.     const sessions = ref([]); // 存储会话列表
  44.     const currentSession = ref({ title: '请开始新的会话', messages: [], loading: false, timeout: false, conversationKey: '' }); // 当前会话
  45.     const sendMessage = async () => {
  46.       if (!userMessage.value.trim()) return;
  47.       const params = {
  48.         conversationKey: currentSession.value.conversationKey,
  49.         message: userMessage.value,
  50.       };
  51.       currentSession.value.messages.push({ role: 'user', content: userMessage.value });
  52.       userMessage.value = '';
  53.       currentSession.value.loading = true;
  54.       currentSession.value.timeout = false;
  55.       const timeoutPromise = new Promise((_, reject) => {
  56.         setTimeout(() => {
  57.           currentSession.value.timeout = true;
  58.           currentSession.value.loading = false;
  59.           reject(new Error('请求超时'));
  60.         }, 120000);
  61.       });
  62.       try {
  63.         const response = await Promise.race([chat(params), timeoutPromise]);
  64.         currentSession.value.messages.push({ role: 'assistant', content: response.data });
  65.       } catch (error) {
  66.         console.error("发送消息失败:", error.message);
  67.         if (error.message !== '请求超时') {
  68.           currentSession.value.messages.push({ role: 'assistant', content: '请求失败,请重试。' });
  69.         }
  70.       } finally {
  71.         currentSession.value.loading = false;
  72.         nextTick(() => {
  73.           const messagesContainer = document.querySelector('.messages');
  74.           messagesContainer.scrollTop = messagesContainer.scrollHeight;
  75.         });
  76.       }
  77.     };
  78.     const startNewSession = async () => {
  79.       if (sessions.value.length >= 10) {
  80.         alert('最多只能创建10个会话!');
  81.         return;
  82.       }
  83.       try {
  84.         const key = await getKey();
  85.         if (!key || !key.data) {
  86.           console.error("获取的会话密钥无效");
  87.           alert('无法创建会话,获取的密钥无效,请稍后再试。');
  88.           return;
  89.         }
  90.         const newSession = {
  91.           title: `会话 ${sessions.value.length + 1}`,
  92.           messages: [],
  93.           loading: false,
  94.           timeout: false,
  95.           conversationKey: key.data,
  96.         };
  97.         sessions.value.push(newSession);
  98.         loadSession(sessions.value.length - 1);
  99.       } catch (error) {
  100.         console.error("获取会话密钥失败:", error.message);
  101.       }
  102.     };
  103.     const loadSession = (index) => {
  104.       currentSession.value = sessions.value[index];
  105.     };
  106.     const deleteSession = async (index) => {
  107.       try {
  108.         const params = {
  109.           conversationKey: sessions.value[index].conversationKey
  110.         }
  111.         await clearConversation(params);
  112.         sessions.value.splice(index, 1);
  113.         if (sessions.value.length > 0) {
  114.           loadSession(0);
  115.         } else {
  116.           currentSession.value = { title: '请开始新的会话', messages: [], loading: false, timeout: false, conversationKey: '' };
  117.         }
  118.       } catch (error) {
  119.         console.error("删除会话失败:", error.message);
  120.       }
  121.     };
  122.     onMounted(() => {
  123.       startNewSession();
  124.     });
  125.     return {
  126.       userMessage,
  127.       sendMessage,
  128.       sessions,
  129.       currentSession,
  130.       startNewSession,
  131.       loadSession,
  132.       deleteSession,
  133.     };
  134.   },
  135. };
  136. </script>
  137. <style>
  138. #app {
  139.   margin-top: 50px;
  140.   display: flex;
  141.   justify-content: center; /* 水平居中 */
  142.   height: 80%;
  143.   width: 70%; /* 设置宽度 */
  144. }
  145. .sidebar {
  146.   width: 250px;
  147.   border-right: 1px solid #ccc;
  148.   padding: 10px;
  149. }
  150. .chat-container {
  151.   flex: 1;
  152.   display: flex;
  153.   flex-direction: column;
  154.   padding: 10px;
  155. }
  156. .chat-title {
  157.   font-size: 24px;
  158.   font-weight: bold;
  159.   margin-bottom: 20px;
  160. }
  161. .messages {
  162.   flex: 1;
  163.   overflow-y: auto; /* 允许垂直滚动 */
  164.   margin-bottom: 10px;
  165.   max-height: 500px; /* 设置最大高度 */
  166. }
  167. .message {
  168.   margin: 5px 0;
  169. }
  170. .message.user {
  171.   text-align: right;
  172.   color: green;
  173. }
  174. .message.assistant {
  175.   margin: 10px;
  176.   text-align: left;
  177.   color: #333;
  178. }
  179. .input-container {
  180.   display: flex;
  181. }
  182. input {
  183.   flex: 1;
  184.   padding: 10px;
  185.   border: 1px solid #ccc;
  186.   border-radius: 4px;
  187.   height: 30px;
  188. }
  189. button {
  190.   padding: 10px;
  191.   margin-left: 5px;
  192.   border: none;
  193.   background-color: #42b983;
  194.   color: white;
  195.   border-radius: 4px;
  196.   cursor: pointer;
  197. }
  198. button:disabled {
  199.   background-color: #ccc;
  200.   cursor: not-allowed;
  201. }
  202. button:hover:not(:disabled) {
  203.   background-color: #369e77;
  204. }
  205. </style>
复制代码
.ts
  1. import { get, post } from "@/config/request";
  2. interface ContextParams {
  3.   conversationKey: string;
  4.   message: string;
  5. }
  6. export function chat(params: ContextParams) {
  7.   return get("api/getChatRedisContext", params);
  8. }
  9. export function getKey() {
  10.   return get("api/getKey");
  11. }
  12. export function clearConversation(params: ContextParams) {
  13.   return get("api/clearConversation", params);
  14. }
复制代码
config
  1. /* eslint-disable @typescript-eslint/no-explicit-any */
  2. import axios, {
  3.   type AxiosInstance,
  4.   type AxiosRequestConfig,
  5.   type AxiosResponse,
  6. } from "axios";
  7. const commonurl = import.meta.env.VITE_APP_BASE_API;
  8. const envType = import.meta.env.VITE_ENV_SET;
  9. // const router = useRouter()
  10. interface resType {
  11.   code: number;
  12.   msg: string;
  13.   data: any;
  14. }
  15. const getBaseUrl = (): string => {
  16.   if (envType === "dev") {
  17.     return commonurl;
  18.   }
  19.   return `https://api.example.com`;
  20. };
  21. const instance = axios.create({
  22.   baseURL: "",
  23.   timeout: 120000,
  24. });
  25. // 添加请求拦截器
  26. instance.interceptors.request.use(
  27.   (config: AxiosRequestConfig): any => {
  28.     // const { userDetil } = storeToRefs(userInfoStore());
  29.     // const Authorization = userDetil.value.Authorization;
  30.     // if (!Authorization && config.url?.indexOf("sys/login") === -1) {
  31.     //   const herf = window.location.href;
  32.     //   const baseUrl = window.location.href.split("#")[0];
  33.     //   const url = `${baseUrl}#/login`;
  34.     //   window.location.replace(url);
  35.     //   showError("用户未登录请重新登录!");
  36.     //   return {};
  37.     // }
  38.     config.headers = {
  39.       "Content-Type": "application/json",
  40.       // Authorization: String(Authorization),
  41.       ...config.headers,
  42.     };
  43.     return config;
  44.   },
  45.   (error: unknown): Promise<any> => {
  46.     // 对请求错误做些什么
  47.     return Promise.reject(error);
  48.   }
  49. );
  50. instance.interceptors.response.use(
  51.   (response: AxiosResponse<resType>): any => {
  52.     const data = response.data;
  53.     if (data.code === 501) {
  54.       showError("账号密码错误!" + `系统提示:${data.msg}`);
  55.       return Promise.reject();
  56.     }
  57.     if (data.code === 500) {
  58.       showError(`系统提示:${data.msg}`);
  59.       return Promise.reject();
  60.     }
  61.     return response;
  62.   },
  63.   (error: any) => {
  64.     if (
  65.       error.response &&
  66.       (error.response.status === 501 ||
  67.         error.response.status === 404 ||
  68.         error.response.status === 401)
  69.     ) {
  70.       const herf = window.location.href;
  71.       const baseUrl = window.location.href.split("#")[0];
  72.       const url = `${baseUrl}#/login`;
  73.       window.location.replace(url);
  74.       showError(error.message);
  75.       return Promise.reject();
  76.     }
  77.     return Promise.reject(error);
  78.   }
  79. );
  80. export const get = <T>(url: string, params?: any): any => {
  81.   return instance.get<T>(url, { params });
  82. };
  83. export const post = <T>(url: string, data?: any): any => {
  84.   return instance.post<T>(url, data);
  85. };
复制代码
这里的封装配置可能差别,可以自行使用,主要就是调用上面的几个接口
功能比力简陋,还在连续完善中,希望大佬多多指教(手动抱拳)


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
继续阅读请点击广告

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
回复

使用道具 举报

© 2001-2025 Discuz! Team. Powered by Discuz! X3.5

GMT+8, 2025-7-25 08:10 , Processed in 4.508744 second(s), 39 queries 手机版|qidao123.com技术社区-IT企服评测▪应用市场 ( 浙ICP备20004199 )|网站地图

快速回复 返回顶部 返回列表