安装“cors-anywhere”包,并在需要跨域请求的代码中添加以下代码:
const proxyUrl = 'https://cors-anywhere.herokuapp.com/';
const targetUrl = 'http://example.com';
fetch(proxyUrl + targetUrl)
.then(response => /*处理响应*/)
.catch(error => /*处理错误*/)
此代码将创建一个代理URL(“proxyUrl”),以帮助您解决跨域问题。您只需将目标URL(“targetUrl”)替换为您的API URL即可。
在您的代理服务器上设置CORS(跨域资源共享)首部,并将其添加到所接收的任何请求的响应中。这是一些可能放在您代理服务器代码中的示例代码:
app.get('/', function(req, res) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.send('Welcome to my API!');
});
以上代码中,“Access-Control-Allow-Origin”设置允许在任何域中访问您的API。如果您只想允许特定域,则可以将“*”替换为适当的域。
无论您采取哪种方法,解决CORS问题的最佳方法可能是使用代理服务器来完成这项工作。
上一篇:本地主机的Cookie域
下一篇:本地主机的CORS问题?