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

使用Fetch API从URL获取前端数据遇错:GET请求不可带Body

问题描述

我需要从指定URL获取数据并在前端展示,该请求在Postman中可正常运行,但执行以下JavaScript代码时出现错误:

async function postData(url = '', data = {}) {
    const response = await fetch(url, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
            "X-Auth-Token": 'abc'
        },
        body: JSON.stringify(data)
    });
    console.log(response.json());
}

postData('url', { answer: 42 });

错误信息:

Uncaught (in promise) TypeError: Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body.
at postData (index.js:3:28)
at index.js:14:1

错误提示翻译:使用GET/HEAD方法的请求不能包含请求体。

解决方案

HTTP规范里明确GET/HEAD请求不允许携带请求体,Postman为了兼容性会放行这种不规范请求,但浏览器的fetch API严格遵循标准,所以直接报错。给你两种解决思路:

  1. 改用POST请求(后端支持的情况下)
    如果后端接口允许用POST方式获取数据,直接修改请求方法,保留原有请求体配置即可,另外注意要await解析JSON的Promise才能拿到实际数据:
async function postData(url = '', data = {}) {
    const response = await fetch(url, {
        method: 'POST', // 改为POST方法
        headers: {
            'Content-Type': 'application/json',
            "X-Auth-Token": 'abc'
        },
        body: JSON.stringify(data)
    });
    const result = await response.json(); // 加await获取解析后的数据
    console.log(result);
}

postData('url', { answer: 42 });
  1. 将参数转为URL查询字符串(必须用GET的情况)
    如果只能用GET请求,就把要传递的参数拼到URL的查询参数里,同时去掉body配置:
async function getData(url = '', params = {}) {
    // 把对象参数转为查询字符串
    const searchParams = new URLSearchParams(params);
    const fullUrl = `${url}?${searchParams.toString()}`;
    
    const response = await fetch(fullUrl, {
        method: 'GET',
        headers: {
            "X-Auth-Token": 'abc'
            // GET请求无需Content-Type头,因为没有请求体
        }
    });
    const result = await response.json();
    console.log(result);
}

getData('url', { answer: 42 });

内容的提问来源于stack exchange,提问作者Nagaprasad T S

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 03:51:42