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跨域限制,通过以下两步解决:
- 后端(PHP)添加跨域允许头
在API接口(如users.php)中添加响应头:
header('Access-Control-Allow-Origin: *');
- 前端调整请求配置
注释掉请求中的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
相关产品推荐
相关产品推荐

