我正在使用 Dribble 的 API 并收到此错误消息:
XMLHttpRequest cannot load https://dribbble.com/oauth/token?client_id=08b8dec4ee5c7af3edd96e0a27eb97f8…a739&code=2806099a944253b647afe25ba384d68a90ca04158a1d1dceadddfe076de941f0. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:3000' is therefore not allowed access.
我已经尝试了很多不同的方法来设置
Access-Control-Allow-Origin = '*'
,但没有一个对我有用,但是阅读console.log(res._headers)我可以看到它正在被定义,我通过POST请求发送它但是标题不起作用。这是我在 Express v4 上的 app.js 中定义的设置标头的方法之一。
app.all("/", function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With");
res.header("Access-Control-Allow-Methods", "GET, PUT, POST, OPTIONS");
res.header("Access-Control-Expose-Headers", "ETag, Link, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset");
res.header("Access-Control-Max-Age", "86400");
res.header("Access-Control-Allow-Credentials", true);
return next();
});
这就是我使用 Axios 发送 POST 请求的方式:
export const postUserOAUTH = code => ((dispatch) => {
axios({
url: `https://dribbble.com/oauth/token?client_id=${clientId}&client_secret=${clientSecret}&code=${code}`,
method: 'post',
}).then((response) => {
dispatch({ type: 'shots', payload: { registerResponse: response.data, token: response.data.access_token } });
console.log('ok')
}).catch((error) => {
dispatch({ type: 'shots', payload: { registerResponse: error.message } });
console.log('error')
});
});
编辑: 现在问题发生了一些变化,代码状态为 200,我收到了 API 根据我的请求响应的令牌,但仍然有相同的错误,代码仍在
.catch
中而不是在 .then
中,我有附上的链接。我不认为这是一个关于身份验证的问题,因为我现在得到了我想要的响应,但是由于这个错误,我无法在代码中使用承诺。 第 2 步。Dribbble 重定向回您的网站。
看起来您正在尝试在 response 对象而不是请求上设置标头(并且您尝试设置的标头是服务器将在成功的 CORS 请求上设置的标头)。相反,试试这个:
app.all("/", function(req, res, next) {
req.header("Origin", "*"); // ideally the '*' will be your hostname
return next();
});
服务器应该使用您尝试在对象上设置的标头进行响应。
免责声明:我不了解 Express,这段代码可能无法按编写的方式工作,但希望您能明白。
有关 CORS 的更多信息,请查看:https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
此外,您还可以在此处查看我们设置
Origin
标头的示例:http://developer.dribbble.com/v1/#cross-origin-resource-sharing
干杯,
伊恩
开发者@Dribbble