我正在构建一个 React 应用程序,并且正在尝试调用 https://itunes.apple.com/search?term=jack+johnson
我有一个名为 requestHelper.js 的助手,它看起来像:
import 'whatwg-fetch';
function parseJSON(response) {
return response.json();
}
function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response;
}
const error = new Error(response.statusText);
error.response = response;
throw error;
}
export default function request(url, options) {
return fetch(url, options)
.then(checkStatus)
.then(parseJSON);
}
所以我得到:
XMLHttpRequest cannot load https://itunes.apple.com/search?term=jack%20johnson. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
我的 express 服务器如下所示:
const ip = require('ip');
const cors = require('cors');
const path = require('path');
const express = require('express');
const port = process.env.PORT || 3000;
const resolve = require('path').resolve;
const app = express();
app.use(cors());
app.use('/', express.static(resolve(process.cwd(), 'dist')));
app.get('*', function(req, res) {
res.sendFile(path.resolve(resolve(process.cwd(), 'dist'), 'index.html'))
});
// Start app
app.listen(port, (err) => {
if (err) {
console.error(err.message);
return false;
}
const divider = '\n-----------------------------------';
console.log('Server started ✓');
console.log(`Access URLs:${divider}\n
Localhost: http://localhost:${port}
LAN: http://${ip.address()}:${port}
${divider}
`);
});
我尝试过使用 mode: 'no-cors'
但实际上并不是我需要的,因为响应为空。
我的这个配置有问题吗?
最佳答案
当 A 上托管的代码向 B 发出请求时,同源策略就会生效。
在本例中,A 是您的 Express 应用程序,B 是 iTunes。
CORS 用于允许 B 向 A 上的代码授予读取响应的权限。
您正在 A 上设置 CORS。这没有任何用处,因为您的站点无法授予客户端代码从其他站点读取数据的权限。
您需要在 B 上进行设置。由于您(大概)不为 Apple 工作,因此您无法执行此操作。只有 Apple 可以授予您的客户端代码从其服务器读取数据的权限。
使用服务器端代码读取数据。
关于javascript - express + cors() 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40747311/