CORS问题,当客户端调用服务器调用外部api



我正在尝试为spotify api实现一个0Auth 2.0流。

如果我从我的客户端调用我的节点服务器,我得到一个cors问题,但如果直接导航到我的服务器url,它工作正常。

这是我在开发工具中尝试

时得到的错误
localhost/:1 Access to XMLHttpRequest at 'https://accounts.spotify.com/authorize?client_id=eca82f597115423cac9d1125e0fb97c4&response_type=code&redirect_uri=http://localhost:8888/callback&scope=user-top-read' (redirected from 'http://localhost:3000/login') from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

服务器在localhost:8888上运行Client on:3000

服务器:

var SpotifyWebApi = require("spotify-web-api-node");
var cors = require("cors");
const express = require("express");
const app = express();
app.use(cors({ origin: "http://localhost:8888" }));
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "localhost:8888"); // update to match the domain you will make the request from
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
});
const scopes = ["user-top-read"];
var spotifyApi = new SpotifyWebApi({
clientId: "eca82f597115423cac9d1125e0fb97c4",
clientSecret: "17a6e5916bb3424eb50f29e4816521a4",
redirectUri: "http://localhost:8888/callback",
});
app.get("/login", (req, res) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, OPTIONS, PUT, PATCH, DELETE"
); // If needed
res.setHeader(
"Access-Control-Allow-Headers",
"X-Requested-With,content-type"
); // If needed
res.setHeader("Access-Control-Allow-Credentials", true);

//ISSUE IS HERE
if (!spotifyApi.getAccessToken()) {
res.redirect(spotifyApi.createAuthorizeURL(scopes));
} else {
res.send("ass");
}
});
app.get("/callback", (req, res) => {
console.log(res);
const error = req.query.error;
const code = req.query.code;
const state = req.query.state;
if (error) {
console.error("Callback Error:", error);
res.send(`Callback Error: ${error}`);
return;
}
spotifyApi
.authorizationCodeGrant(code)
.then((data) => {
const access_token = data.body["access_token"];
const refresh_token = data.body["refresh_token"];
const expires_in = data.body["expires_in"];
spotifyApi.setAccessToken(access_token);
spotifyApi.setRefreshToken(refresh_token);
console.log("access_token:", access_token);
console.log("refresh_token:", refresh_token);
console.log(
`Sucessfully retreived access token. Expires in ${expires_in} s.`
);
res.send("Success! You can now close the window.");
setInterval(async () => {
const data = await spotifyApi.refreshAccessToken();
const access_token = data.body["access_token"];
spotifyApi.setAccessToken(access_token);
}, (expires_in / 2) * 1000);
})
.catch((error) => {
console.error("Error getting Tokens:", error);
res.send(`Error getting Tokens: ${error}`);
});
});
app.get("/getTopTracks", (req, res) => {
spotifyApi.getMyTopTracks().then(function (data) {
res.send(data.body.items);
});
});
app.listen(8888, () =>
console.log(
"HTTP Server up. Now go to http://localhost:8888/login in your browser."
)
);

客户:

function FunctionalComponent() {
const [topTracks, settopTracks] = useState([]);
function handleOnClick() {
axios.get("/login").then((res) => {
console.log(res);
});
}
return (
<div>
<button onClick={handleOnClick}>Click here to login</button>
</div>
);
}
export default FunctionalComponent;

from MDN:For security reasons, browsers restrict cross-origin HTTP requests initiated from scripts. For example, XMLHttpRequest and the Fetch API follow the same-origin policy.

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

所以正如你所理解的,这个限制来自浏览器阻止跨源域的请求,特别是来自脚本的请求,而不是来自导航url本身,因为它不是来自脚本。

相关内容

  • 没有找到相关文章

最新更新