Skip to main content

网络请求 Network

此模块封装了基于 fetch 的网络请求工具,支持 GETPOSTPUTDELETE 请求,并内置了 token 管理、请求 loading 控制、流式请求支持、中断机制与国际化错误提示等功能。


实际使用

💡 配置服务器 ip

📚src/services/stream.js

配置为自己的服务器信息

export const config = {
baseURL: 'http://50.105.103.100:20191/api/', //服务器 接口前缀
timeout: 60000, //超时时间 ms
ip: '', //其它参数
};

📤 普通请求

📚src/services/user.js

/* 登录 */
export const requestLogin = (data) => post('usercenter/v1/user/login', data);

📚 登录页面

import React from 'react';

import { requestLogin } from '@/services/user';

function LoginIndex() {
//登录
const onSubmit = async (values) => {
const res = await requestLogin(values);

if (res?.Code !== 200) {
res?.Message && message.warning(res?.Message);

return;
}

//存储token
dispatch(onSetState({ token: res?.Data?.accessToken, account: values.account }));
};
}

🔁 流式响应

📚src/services/public.js

/* 对话 流式请求 deepseek V3 腾讯云 */
export const requestSteamSessionGTV3 = (data, callback, params) =>
post('https://api.lkeap.cloud.tencent.com/v1', data, callback, params);

📚 组件内或其他工具函数内

import React, { useCallback, useEffect, useRef, useState } from 'react';

import { requestSteamSessionGTV3 } from '@/services/public';

import { onSetState } from '@/components/system';

function getStreamData() {
const authorizationTIRef = useRef('Bearer sk-0FdWYS0A1Otc'); //腾讯云
const controllerRef = useRef(new AbortController()); //控制流式中断
const dialogIdRef = useRef(0);

const [messageList, setMessageList] = useState({});

//中断流式响应
const onStopStream = useCallback((callback = () => {}) => {
controllerRef.current.abort();
callback(true);
}, []);

//流式接收响应数据
const onChangeMessage = useCallback((content) => {
//渲染返回数据 这里可以写任何想实现的逻辑
setMessageList((prev) => {
const msgList = { ...prev, contentList: [...prev.contentList] };

if (msgList.contentList?.length > 0) {
const lastIndex = msgList.contentList.length - 1;

msgList.contentList[lastIndex] = {
...msgList.contentList[lastIndex],
content,
};
}

return msgList;
});
}, []);

//更新dom - 流式加载响应数据
const sendCallback = useCallback(
async (content, done) => {
if (content && content !== '- 停止接收') {
resContentRef.current = [...resContentRef.current, ...content];
onChangeMessage(resContentRef.current);
}

dispatch(
onSetState({
dialogId: dialogIdRef.current,
}),
);
},
[dispatch, onChangeMessage],
);

function send() {
const params = {
messages: [{ content: '你好', role: 'user' }],
model: 'deepseek-v3',
max_tokens: 4096,
top_k: 50,
top_p: 0.7,
temperature: 0.5,
};

//调用流式请求方法
requestSteamSessionGTV3(params, sendCallback, {
controller: controllerRef.current,
authorization: authorizationTIRef.current,
stream: true, //设为true为流式响应
loading: false,
}).then();
}

useEffect(() => {
send();
}, []);

return <div>{messageList}</div>;
}

结构说明

📦 导出内容

export const config;
export async function get(url, params);
export async function post(url, data, callback?, params?);
export async function put(url, data, callback?, params?);
export async function del(url, params?);

🔧 配置项:config

config = {
aiBaseURL: 'http://50.105.103.100:20191/api/',
baseURL: 'http://50.105.103.100:20191/api/',
timeout: 60000, // 请求超时时间(毫秒)
ip: '',
};

⚙️ 请求参数配置:params

每个请求函数都可以传入一个配置对象:

参数类型默认值说明
authorizationstring''自定义 Token
controllerAbortControllernull用于中断请求
streambooleanfalse是否为流式请求(仅 post 支持)
typestring'json'返回数据格式(支持 json, text, blob 等)
urlTypestring'baseURL'使用哪个基础地址(支持 baseURL / aiBaseURL
loadingbooleantrue是否自动显示 loading 遮罩

📤 POST 请求

await post('/chat/completion', { prompt: '你好' }, callback, {
stream: true,
controller: new AbortController(),
});

📚 支持流式响应(如 ChatGPT 流)

  • callback(dataChunk, done)
    • dataChunk:每次返回的流内容数组
    • done:是否流结束

📥 PUT 请求

await put('/user/update', { name: '张三' }, (res) => {
console.log('更新结果:', res);
});

📄 GET 请求

const data = await get('/user/info', {
loading: false,
});

❌ DELETE 请求

await del('/message/123', {
urlType: 'aiBaseURL',
});

🔁 中断请求(流式专用)

const controller = new AbortController();

post('/chat/completion', data, callback, {
stream: true,
controller,
});

// 需要中断时调用
controller.abort();

💡 自动处理内容

  • 自动附带全局 Token:从zustand useGlobalStore.getState().token 获取
  • 返回状态码处理(如 401 重定向至登录页)
  • 错误统一提示(通过 message.error + 国际化处理)
  • 请求 loading 状态统一调用 setLoading(true/false)
  • 统一超时处理(默认 60 秒)

🧪 注意事项

  • 所有请求都自动附带 Content-Type: application/json
  • 对 undefined 请求体字段会自动转为 null
  • 异常情况会显示错误提示并可自定义处理方式
  • 如果你使用的是流式请求,请确保接口支持 text/event-streamchunked transfer encoding