问题背景: 当我们在本地主机上的网页中使用fetch请求访问外部的API时,有时会遇到CORS(跨源资源共享)策略阻止的问题。这是因为浏览器根据安全策略,限制了跨域的请求。
解决方法: 有几种方法可以解决这个问题,下面给出其中两种常见的方法。
方法一:使用代理服务器 通过设置一个代理服务器来转发请求,使得请求看起来是从同一个域名下发出的,从而绕过CORS策略的限制。
示例代码:
// 代理服务器代码(使用Node.js和Express框架) const express = require('express'); const request = require('request');
const app = express();
app.get('/api/proxy', (req, res) => { const url = 'https://external-api.com'; // 目标API的URL request(url, (error, response, body) => { if (!error && response.statusCode === 200) { res.send(body); } else { res.status(response.statusCode).send(error); } }); });
app.listen(3000, () => { console.log('Proxy server is running on port 3000'); });
// 前端代码 fetch('/api/proxy') .then(response => response.json()) .then(data => { console.log(data); }) .catch(error => { console.error(error); });
方法二:在服务器端设置响应头 在目标API的服务器端设置允许跨域请求的响应头,从而绕过CORS策略的限制。
示例代码(Node.js和Express框架):
const express = require('express'); const app = express();
app.get('/api/data', (req, res) => { // 设置响应头,允许所有域名的请求 res.header("Access-Control-Allow-Origin", "*");
// 处理请求,并返回响应数据 res.json({ message: 'Hello, World!' }); });
app.listen(3000, () => { console.log('Server is running on port 3000'); });
// 前端代码 fetch('http://localhost:3000/api/data') .then(response => response.json()) .then(data => { console.log(data); }) .catch(error => { console.error(error); });
以上是两种常见的解决方法,选择适合自己需求的方法来解决CORS策略阻止的问题。