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

React向本地3001服务器Fetch请求报Unexpected end of input错误

解决Fetch请求本地服务器时"Unexpected end of input"错误

问题根源分析

  • Fetch的no-cors模式限制响应读取:设置mode: 'no-cors'后,浏览器会将响应标记为不透明响应,无法访问响应内容、状态码等信息,调用res.json()必然解析失败,抛出目标错误。
  • CORS中间件顺序错误:服务器中app.use(allowCrossDomain)放在路由定义之后,导致路由执行时CORS头还未设置,浏览器仍会触发CORS限制,这也是你误以为需要no-cors模式的原因。
  • 服务器重复发送响应:当objects不存在时,先执行res.status(404).send(),后续还会执行res.status(200).send(objects),导致Express尝试发送两次响应,可能引发响应内容异常。

修复步骤

1. 修正Fetch请求代码

去掉no-cors模式,同时编码查询参数避免特殊字符问题,增加错误捕获:

import updateOnSearchRequest from '../redux/actions/updateOnSearchRequest';

export default function searchRequestToApi(queryText, dispatch) {
    fetch(`http://localhost:3001/${encodeURIComponent(queryText)}`)
        .then(res => {
            if (!res.ok) {
                throw new Error('请求失败');
            }
            return res.json();
        })
        .then(data => dispatch(updateOnSearchRequest(data)))
        .catch(err => console.error('请求出错:', err));
}

2. 调整服务器代码

修正中间件顺序,优化响应逻辑:

const SerpApi = require('google-search-results-nodejs');
const search = new SerpApi.GoogleSearch("myApiKey");
const express = require('express');
const app = express();

var allowCrossDomain = function (req, res, next) {
    res.header('Access-Control-Allow-Origin', "*");
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    next();
}

// 先应用CORS中间件,再定义路由
app.use(allowCrossDomain);

app.get('/:id', function (req, res) {
    console.log("Made request");
    const searchText = req.params.id;

    const params = {
        q: searchText,
        tbm: "shop",
    };

    const callback = function (data) {
        const objects = data["shopping_results"] ? [...data["shopping_results"]] : null;
        console.log("call back worked");

        if (!objects) {
            console.log("ERROR 404");
            return res.status(404).json({ error: "No results found" });
        }

        res.status(200).json(objects);
    };

    search.json(params, callback);
});

app.listen(3001, function () {
    console.log("App is listening for queries");
})

修改说明:

  • 将CORS中间件移至路由定义前,确保路由处理前已设置CORS头
  • 用res.json()替代res.send(),自动设置Content-Type: application/json响应头
  • 当无结果时用return终止后续代码,避免重复发送响应
  • 优化objects的判断逻辑,防止解构undefined报错

3. 验证修复

重启本地服务器后,从React应用发起请求,即可正常获取数据,不再出现"Unexpected end of input"错误。

内容的提问来源于stack exchange,提问作者Good guy from world

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 09:16:15