可能是由于浏览器的跨域安全策略限制导致的。可以尝试使用代理或在API Gateway上启用CORS来解决该问题。
以下是一些通过代理解决该问题的代码示例:
在服务器端启用代理:
const express = require('express');
const request = require('request');
const app = express();
app.use('/', (req, res) => {
const url = 'https://myapi.com' + req.url;
req.pipe(request(url)).pipe(res);
});
app.listen(3000, () => { console.log('Proxy server started.') });
在客户端使用代理:
const proxyUrl = 'http://localhost:3000';
fetch(proxyUrl + '/my-api-endpoint')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
在API Gateway上启用CORS:
在API Gateway的设置中,添加以下CORS配置:
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET
Access-Control-Allow-Headers: Content-Type
这将允许所有源的请求访问API。如果需要更加细粒度的控制,可以将*
替换为具体的源地址。