给所有请求都加上jwt,隐藏生成jwt的secret(放到.env中),隐藏app-secret(放在pm2运行配置文件中,后续直接读取环境配置即可)
This commit is contained in:
@@ -0,0 +1,55 @@
|
||||
import { type LoaderFunctionArgs } from "@remix-run/node";
|
||||
import { getUserSession } from "~/api/login/auth.server";
|
||||
import { DOCUMENT_URL } from "~/api/axios-client";
|
||||
|
||||
/**
|
||||
* PDF 代理路由
|
||||
* 用于在服务器端添加 JWT 认证后获取 PDF 文件
|
||||
*/
|
||||
export async function loader({ request }: LoaderFunctionArgs) {
|
||||
try {
|
||||
// 获取 JWT token
|
||||
const { frontendJWT } = await getUserSession(request);
|
||||
|
||||
// 从查询参数获取文件路径
|
||||
const url = new URL(request.url);
|
||||
const filePath = url.searchParams.get("path");
|
||||
|
||||
if (!filePath) {
|
||||
return new Response("缺少文件路径参数", { status: 400 });
|
||||
}
|
||||
|
||||
// 构建完整的文件 URL
|
||||
const fileUrl = `${DOCUMENT_URL}${filePath}`;
|
||||
|
||||
// 使用 JWT 认证获取文件
|
||||
const response = await fetch(fileUrl, {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${frontendJWT}`,
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
return new Response(`获取文件失败: ${response.statusText}`, {
|
||||
status: response.status
|
||||
});
|
||||
}
|
||||
|
||||
// 获取文件内容
|
||||
const blob = await response.blob();
|
||||
|
||||
// 返回文件,保持原始的 Content-Type
|
||||
return new Response(blob, {
|
||||
headers: {
|
||||
'Content-Type': response.headers.get('Content-Type') || 'application/pdf',
|
||||
'Cache-Control': 'public, max-age=3600', // 缓存1小时
|
||||
},
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('PDF 代理错误:', error);
|
||||
return new Response(`服务器错误: ${error instanceof Error ? error.message : '未知错误'}`, {
|
||||
status: 500
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user