I’m building a react application using Spotify API, I need to get the token after authorization to my react application. The authorization for spotify open in a new window and closes after authorization and need to send back the token to my react app. I’ve wriiten the backend code in Flask.
Authorization and Callback route:
@app.route("/authorize_spotify")
def authorize_spotify():
auth_url = sp_oauth.get_authorize_url()
return jsonify({"auth_url": auth_url})
@app.route("/callback")
def callback():
code = request.args.get('code')
token_info = sp_oauth.get_access_token(code)
token_info_json = jsonify(token_info).json
token_info_json_str = json.dumps(token_info_json)
close_window_script = """
<script>
window.opener.postMessage({token_info_json_str}, window.location.origin);
window.close();
</script>
"""
return close_window_script
In my react application I’ve a button to handle authorization,
const handleAuthClick = async () => {
try {
const response = await fetch("http://localhost:5000/authorize_spotify");
const data = await response.json();
const authWindow = window.open(data.auth_url, "", "width=450,height=300");
window.addEventListener("message", (event) => {
const { token } = event.data;
console.log(token);
setAuthorized(true);
authWindow.close();
});
} catch (error) {
console.error("Error:", error);
}
};
the callback window didn’t close, and I’m getting error as
Uncaught SyntaxError: Unexpected token ‘<‘