React Native获取Spotify Access Token时持续出现400错误求助
React Native + Expo Spotify 令牌获取问题
我在为React Native应用获取Spotify的access token和refresh token时遇到了问题。按照Expo官方Spotify认证文档,已经通过useAuthRequest拿到了code和state。一开始尝试在客户端用code换token,一直报400错误;改成用Express服务器处理后,还是报错。
服务端代码
router.post('/get-spotify-access-code',(req: Request, res: Response)=>{ console.log(req.body) const accessCode = req.body; var authOptions:AuthOptions = { url: 'https://accounts.spotify.com/api/token', form: { code: accessCode, redirect_uri: redirectUri, grant_type: 'authorization_code' }, headers: { 'content-type': 'application/x-www-form-urlencoded', 'Authorization': 'Basic ' + Buffer.from(clientID + ':' + clientSecret).toString('base64') }, json: true }; request.post(authOptions, (error: any, response:any, body:any)=>{ console.log(error); console.log(response) if(!error && response.statusCode === 200){ const access_token = body.access_token; const refresh_token = body.refresh_token; const expires_in = body.expires_in; res.json({ 'access_token': access_token, 'refresh_token': refresh_token, 'expires_in': expires_in }); } }) })
客户端代码
const [request2, response2, promptAsync2] = useAuthRequest({ clientId: clientID, clientSecret: clientSecret, scopes: [ 'user-read-playback-state', 'user-modify-playback-state', 'user-read-currently-playing', 'streaming', 'playlist-read-private', 'playlist-read-collaborative', 'playlist-modify-private', 'playlist-modify-public', 'user-follow-modify', 'user-follow-read', 'user-read-playback-position', 'user-library-modify', 'user-library-read', 'user-read-email', 'user-read-private' ], usePKCE: false, redirectUri: makeRedirectUri({ scheme: undefined }) }, discovery ) useEffect(() => { if (response2?.type === 'success') { // get spotify access code const { code } = response2.params; const getSpotifyCode = async() =>{ const code2 = { code } await axios.post('http://localhost:8005/get-spotify-access-code', code2).then( response =>{ console.log(response); } ).catch(error =>{ console.log(error) }) } getSpotifyCode() } }, [response2])
问题排查与修复方案
- 修正服务端code参数:客户端传的是
{ code: xxx },但服务端直接把req.body赋值给accessCode,导致传给Spotify的是对象而非字符串。改成const accessCode = req.body.code;。 - 确保redirect_uri完全一致:服务端的
redirectUri必须和客户端useAuthRequest里的redirectUri完全匹配,包括大小写、末尾斜杠等,Spotify对该参数的匹配要求严格。 - 移除客户端clientSecret:客户端代码中直接暴露
clientSecret存在安全风险,应仅在服务端存储该密钥,客户端只传递code即可。 - 开启PKCE模式:授权码流程建议设置
usePKCE: true,这是更安全的做法,也符合Spotify的最佳实践。 - 查看具体错误信息:在服务端打印
response.body,Spotify会返回具体错误类型(如invalid_grant、redirect_uri_mismatch),可快速定位问题。
内容的提问来源于stack exchange,提问作者Iseoluwa ariyibi
相关产品推荐
相关产品推荐

