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

ReactJS中Fetch在移动端Chrome返回undefined问题排查与解决

ReactJS跨域请求在移动端Chrome返回undefined问题解决

问题描述

我开发的ReactJS网站部署在https://test.mydomain.com子域,所有API请求均指向https://api.mydomain.com子域。网站在桌面浏览器运行正常,但在移动端Chrome浏览器中,API始终返回undefined。

原前端代码

const myFuction= async() => {
    try {
      const API_ENDPOINT = `https://api.mydomain.com/users.php`;
      
const data = await fetch(API_ENDPOINT, {
        method: "POST",
        headers: {
          Accept: "application/json",
          "Content-type": "application/json",
        },
        body: JSON.stringify({
          param1: "PARAM_1",
        }),
      });
      
const users = data.json();

      
      if (users.result.user != undefined) {
        
        console.log("Token OK");

        return true;
      } else {
        console.log("Token ERROR.");
        
        return false;
      }
      
    } catch (error) {
      
      alert(error);
      console.error(error);
    }

    return "ERROR";
  };

解决方法

问题根源是CORS跨域限制,通过以下两步解决:

  1. 后端(PHP)添加跨域允许头
    在API接口(如users.php)中添加响应头:
header('Access-Control-Allow-Origin: *');
  1. 前端调整请求配置
    注释掉请求中的headers部分,修改后的函数代码:
const myFuction= async() => {
     try {
       const API_ENDPOINT = `https://api.mydomain.com/users.php`;

      const data = await fetch(API_ENDPOINT, {
         method: "POST",
         // headers: {
         // Accept: "application/json",
         // "Content-type": "application/json",
         // },
         body: JSON.stringify({
           param1: "PARAM_1",
         }),
      });

      const users = data.json();

       if (users.result.user != undefined) {
         console.log("Token OK");
         return true;
       } else {
         console.log("Token ERROR.");
         return false;
       }

     } catch (error) {
       alert(error);
       console.error(error);
     }
     return "ERROR";
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 15:55:19