使用Fetch API集成GetResponse接口时出现CORS跨域报错无法调用成功
问题根因
- GetResponse V3 API 未配置CORS跨域响应头,本身不支持浏览器端直接发起请求,同源策略会直接拦截这类跨域调用。
- 你当前的写法将API密钥直接硬编码在前端代码中,属于严重的安全隐患,所有访问页面的用户都可以通过调试工具拿到密钥,篡改你的账户数据。
修复方案
- 方案一(生产可用):新增后端服务层做请求转发
前端将联系人参数发送给自己的后端接口,由后端服务携带API密钥请求GetResponse接口,再将结果返回给前端。后端不存在跨域限制,同时密钥保存在服务端不会泄露。
后端Node.js简单实现示例:
前端调整为调用你自己的后端接口即可:const express = require('express'); const fetch = require('node-fetch'); const app = express(); app.use(express.json()); // 允许前端跨域调用你的接口 app.use((req, res, next) => { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'Content-Type'); next(); }) app.post('/add-contact', async (req, res) => { const { name, email } = req.body; const grResponse = await fetch('https://api.getresponse.com/v3/contacts', { method: 'POST', body: JSON.stringify({ campaign: { campaignId: '5D8Qm' }, name, email }), headers: { 'X-Auth-Token': 'api-key 密钥存储在服务端环境变量,不要硬编码', 'Content-Type': 'application/json' } }) const result = await grResponse.json(); res.json(result); }) app.listen(3000);fetch("http://你的后端服务地址/add-contact", { method: "POST", body: JSON.stringify({ name: "xyz", email: "fdfdfd@gmail.com" }), headers: { "Content-type": "application/json" } }) .then(response => response.json()) .then(json => console.log(json)); - 方案二(仅本地调试用):临时关闭浏览器同源校验
本地开发测试时,可以给浏览器添加启动参数--disable-web-security --user-data-dir=本地临时目录关闭同源策略,或者安装CORS调试插件,该方案绝对不能用于生产环境。
内容的提问来源于stack exchange,提问作者Abdullah Al Mamun
相关产品推荐
相关产品推荐

