Files
new-api/web/functions/mj/[[default]].js

35 lines
1.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// functions/Pages_Functions.js
// 该函数会将所有请求转发到环境变量 `TARGET_URL` 指定的地址
export async function onRequest(context) {
// 从上下文中获取原始请求和环境变量
const { request, env } = context;
// 解析原始请求的 URL以获取路径和查询参数
const url = new URL(request.url);
const path = url.pathname;
const search = url.search;
// 从环境变量中获取目标 URL如果未设置则提供一个默认值
const target = env.TARGET_URL || 'http://172.0.0.1';
// 构建目标 URL
const targetUrl = `${target}${path}${search}`;
// 创建一个新的请求以转发到目标地址
// 复制原始请求的方法、头部和主体
const newRequest = new Request(targetUrl, {
method: request.method,
headers: request.headers,
body: request.body,
redirect: 'manual' // 防止 fetch 自动处理重定向
});
// 执行转发请求并返回响应
try {
return await fetch(newRequest);
} catch (error) {
// 如果目标服务器无法访问,返回一个错误信息
return new Response(`Error forwarding request: ${error.message}`, { status: 502 });
}
}