You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SvelteKit 1.0.0-next.483移动端访问本地接口触发TypeError: immutable错误

解决SvelteKit代理接口时移动设备访问触发的TypeError: immutable错误

问题场景

使用SvelteKit 1.0.0-next.483,通过npm run dev -- --host启动项目,移动设备连接本地网络IP访问接口时,出现以下错误:

TypeError: immutable
    at Headers.append ([..]node_modules/undici/lib/fetch/headers.js:227:13)

该错误仅在移动设备通过IP访问时触发,接口代码位于src/routes/gqlendpoint/+server.ts:

const base = 'http://localhost:4000/graphql';

export async function POST( opts: { request: Request} ): Promise<Response> {
    
    const { request } = opts;

    const body =  await request.json(); 

    const response = await fetch(base, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body)
    });

    return response;
}

临时修改node_modules/undici/lib/fetch/headers.js注释报错代码的方式不可取,需采用正确解法。

错误原因

直接返回fetch获取的Response对象时,该Response的headers处于**immutable(不可修改)**的保护状态。当移动设备通过IP访问(属于跨源场景),SvelteKit在后续处理响应时会尝试修改headers(比如添加CORS相关头),触发undici的类型校验错误。而本地通过localhost访问时,框架不会执行这些跨源相关的headers修改逻辑,因此不会报错。

解决方案

重新构造一个新的Response对象,将原响应的状态、状态文本和headers转为可修改的实例后返回,避免原Response的immutable headers限制。

修改后的完整代码:

// 注意:移动设备访问时需将localhost替换为你的电脑本地IP(如192.168.x.x),否则移动设备无法连接后端服务
const base = 'http://localhost:4000/graphql';

export async function POST(opts: { request: Request }): Promise<Response> {
    const { request } = opts;
    const body = await request.json();

    const response = await fetch(base, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body)
    });

    // 重新构造Response,转换immutable headers为可修改实例
    return new Response(response.body, {
        status: response.status,
        statusText: response.statusText,
        headers: new Headers(response.headers)
    });
}

额外提示:若移动设备无法连接到后端GraphQL服务,务必将base中的localhost替换为你的电脑在本地网络的实际IP地址,确保移动设备能正常访问后端服务。

内容的提问来源于stack exchange,提问作者Sten Ka Razin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 14:10:48