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

MERN栈前后端交互问题:前端接收text/html而非JSON

MERN栈请求异常排查:Postman正常但前端Fetch返回text/html

问题背景

  • NodeJS开发后端、ReactJS开发前端,后端部署在本地
  • Postman调用接口可正常获取JSON数据,但前端使用fetch请求时,接口返回text/html类型数据而非JSON

前端代码

class Auth {
    async fetchData() {
        try {
            const response = await fetch('/data/get-data', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            console.log("DEBUG : response", response); // Log the entire response object

            if (!response.ok) {
                throw new Error(`Failed to fetch data: Status code ${response.status}`);
            }

            const contentType = response.headers.get('content-type');
            if (!contentType || !contentType.includes('application/json')) {
                throw new Error('Unexpected content type: ' + contentType);
            }

            const jsonData = await response.json();
            console.log("DEBUG : jsonData", jsonData);
            return jsonData;
        } catch (error) {
            console.error('Error fetching data:', error);
            // 可选:在前端优雅处理错误(比如显示错误提示)
        }
    }
}

const authService = new Auth();
export default authService

后端代码

import { asyncHandler } from '../utils/asyncHandler.js';
import { ApiResponse } from '../utils/apiResponse.js';
import { Data } from '../models/data.model.js';
import { ApiErrors } from '../utils/ApiErrors.js';

const getData = asyncHandler(
    async (req, res) => {
        try {
            const data = await Data.find();

            console.log("\nSuccessfully retrieved data...");
            res.setHeader('Content-Type', 'application/json');
            return res
                .status(200)
                .json(new ApiResponse(200, data,  "Data Sent Successfully!!"));
        } catch (error) {
            console.error('Error while fetching data:', error);
            const apiError = new ApiErrors(500, 'Internal Server Error');
            return res.status(apiError.statusCode).json(apiError);
        }
    }
);

export { getData };

报错信息

auth.js:25 Error fetching data: Error: Unexpected content type: text/html

解决步骤

1. 修正前端请求目标(核心问题)

前端React开发服务器(默认3000端口)和后端Node服务器(比如3001端口)是两个独立服务,直接用相对路径/data/get-data会请求React服务器,而非后端。解决方法二选一:

  • 方法一:使用完整后端URL
    修改fetch的URL为后端服务器地址,比如:
    const response = await fetch('http://localhost:3001/data/get-data', { ... })
    
  • 方法二:配置React代理
    在React项目的package.json中添加代理配置,自动转发请求到后端:
    "proxy": "http://localhost:3001" // 替换为你的后端端口
    
    配置后重启React开发服务器,即可继续使用相对路径/data/get-data。

2. 检查后端路由配置

确认后端的路由是否正确映射到getData函数,比如Express中是否有类似代码:

app.get('/data/get-data', getData);

如果路径不匹配,后端可能返回404页面(text/html)。

3. 排查中间件顺序问题

如果后端使用了express.static中间件,确保它放在路由配置之后,否则静态文件中间件会优先匹配请求,返回HTML文件:

// 错误顺序:静态文件中间件在前
app.use(express.static('public'));
app.get('/data/get-data', getData);

// 正确顺序:路由在前
app.get('/data/get-data', getData);
app.use(express.static('public'));

4. 查看返回的HTML内容

在前端catch块中添加代码,查看返回的HTML具体内容,帮助定位问题:

catch (error) {
    console.error('Error fetching data:', error);
    // 新增:打印返回的HTML内容
    response.text().then(html => console.log('返回的HTML内容:', html));
}

如果返回的是React的404页面,说明请求没转发到后端;如果是后端的错误页面,说明后端路由或逻辑有问题。


内容的提问来源于stack exchange,提问作者Aditya verma

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 10:15:33