Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

jquery - Allowing frontend JavaScript POST requests to https://accounts.spotify.com/api/token endpoint

In order to get an access token for the Spotify API in my web app (as specified by their Web Authorization Flow), I've learned that I have to make a POST request. However, when I do so, I get the XMLHttpRequest 500 Error due to the cross-origin problem.

I have already figured out how to allow CORS GET requests, but am not sure how to do the same for POST requests. This link provides configuration tips, but it leaves the actual routes for GET and POST blank.

This is the relevant code for my Express.js server:

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});



app.use(express.static(__dirname + '/public')); // looks in public directory, not root directory (protects files)

app.get('/', function(req, res) {
  // res.header("Access-Control-Allow-Origin", "*");
  // res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.send(__dirname + '\index.html')
});

app.post('/', function(req, res) {
    res.send(req.body.spotify);
});

(spotify is the spotify-web-api-js node module).

I've previously tried copying the exact code for app.get into app.post, but that caused the server to crash.

This is the bit of code in my program's JavaScript file that intends to send a POST request after the user clicks on a button that takes them to the start of Spotify's authorization path and approves the sign-in:

$('#spotify').on('click', function() {
    $.support.cors = true;

    $.post("https://accounts.spotify.com/api/token");

      });

(in this case, spotify is the ID for the button in the HTML file)

What should I do to bypass the CORS issue in this case? I've been stumped for a few days.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can find an example of using express to perform the authentication flow with Spotify on https://github.com/spotify/web-api-auth-examples (see the authorization_code approach).

You can't get an access token making a client-side request to /api/token. You need to make a request to /authorize, which will redirect to your redirect_uri, which itself will exchange a code with an access token.

Check that example, which should cover your needs.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...