发起HTTP GET请求时遭遇CORS错误,寻求技术解决方案
解决HTTP GET请求中的CORS错误
问题详情
- 客户端运行地址:
http://127.0.0.1:5000/client/contactAdmin.html - 目标API地址:
http://localhost:5000/api/form/contactAdmin - 发起GET请求时触发CORS错误,网络标签页截图:

后端代码
app.use('/api/form', formRoute); router.get('/contactAdmin', async (req, res) => { const allForms = await Form.find({}); return res.status(200).json({ allForms }); });
前端代码
const renderForms = async () => { try { const response = await fetch( 'http://localhost:5000/api/form/contactAdmin', { method: 'GET', headers: { 'Content-type': 'application/json; charset=UTF-8', }, } ); return response; } catch (error) { console.log(error); } }; renderForms();
解决方案
原因说明
浏览器将127.0.0.1和localhost判定为不同的源,即使端口一致,因此触发跨域限制。
方案1:使用相对路径请求API
修改前端fetch的URL为相对路径,自动匹配当前客户端的域名:
const response = await fetch('/api/form/contactAdmin', { method: 'GET', headers: { 'Content-type': 'application/json; charset=UTF-8', }, });
方案2:后端配置CORS中间件
如果需要允许跨源访问,在Express后端中使用cors中间件:
- 安装依赖:
npm install cors
- 引入并配置:
const cors = require('cors'); // 允许所有源访问(开发环境可用) app.use(cors()); // 或严格限制仅指定源访问(生产环境推荐) app.use(cors({ origin: 'http://127.0.0.1:5000' }));
方案3:统一域名映射(不推荐)
修改本地hosts文件,将localhost和127.0.0.1强制关联,但开发环境下前两种方案更简洁高效。
内容的提问来源于stack exchange,提问作者עמית שוקרון
相关产品推荐
相关产品推荐

