Node.js+React项目:Axios发GET请求后端返回空,Postman测试正常
问题:Node.js后端+React前端,GET接口Postman正常但Axios调用返回空值
使用Node.js做后端、React做前端开发时,所有API在Postman测试都能正常返回数据,但前端用Axios调用GET接口时,后端返回空值。
后端(Node.js)跨域配置代码
res.setHeader("Access-Control-Allow-Origin", "*"); res.setHeader( "Access-Control-Allow-Headers", "Origin, X-Requested-With, Content, Accept, Content-Type, Authorization" ); res.setHeader( "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS" ); res.setHeader("Cross-Origin-Resource-Policy", "same-site");
前端(React)Axios请求代码
var data = JSON.stringify({ email: "testapi", }); var config = { method: "get", url: "http://localhost:4000/api/auth", headers: { "Content-Type": "application/json", }, data: data, }; axios(config) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
问题原因与解决办法
核心问题1:GET请求带请求体不符合规范
HTTP规范里,GET请求本就不应该携带请求体。Postman对这个规则兼容性宽松,会把请求体发去后端,但浏览器和Axios处理GET请求时,不会正确传递请求体内容,导致后端收不到email参数,返回空值。
核心问题2:跨域配置冲突
你同时设置了Access-Control-Allow-Origin: *(允许所有跨域请求)和Cross-Origin-Resource-Policy: same-site(限制仅同站点访问),这两个配置互相矛盾,可能导致浏览器对请求的处理异常。
修复步骤
修改Axios GET请求参数传递方式
把参数放到URL的查询字符串里,或者用Axios的params字段自动拼接:
方式一:直接拼接URLvar config = { method: "get", url: "http://localhost:4000/api/auth?email=testapi", headers: { "Content-Type": "application/json", }, }; axios(config) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });方式二:用
params字段var config = { method: "get", url: "http://localhost:4000/api/auth", headers: { "Content-Type": "application/json", }, params: { email: "testapi" } }; axios(config) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });修正跨域配置冲突
删除res.setHeader("Cross-Origin-Resource-Policy", "same-site");这一行,或者把它改为cross-origin,和允许所有跨域的配置保持一致:res.setHeader("Cross-Origin-Resource-Policy", "cross-origin");
内容的提问来源于stack exchange,提问作者Lhony
相关产品推荐
相关产品推荐

