如何在django端口8000中触发OAuth 2.0回调后继续使用react端口3000



我的应用是由React前端和Django后端构建的。

虽然React部分在Django项目的前端文件夹中,但我尽量使这两个部分尽可能独立。

所以基本上,Django只作为API提供服务,React控制整个前端。

在dev模式下,Django运行在本地主机上,端口为8000;React运行在端口3000上。我已经在setting.py

中完成了CORS设置
CORS_ALLOWED_ORIGINS = [
'http://localhost:3000'
]

基本上,我可以独立测试前端和后端。所有的Api抓取在Django和React之间也能正常工作。

然而,在我的应用程序中,我还需要连接到Spotify API来做一些事情。在认证过程中,我需要提供Spotify认证回调的Redirect url。

我在Spotify注册的url是:

http://127.0.0.1:8000/api-spotify/callback

in my urls.py:

from .views import get_auth_callback
urlpatterns = [
path('callback', get_auth_callback),
]

在view.py:

def get_auth_callback(request):
code = request.GET.get('code')
response = post('https://accounts.spotify.com/api/token', data={
'code': code,
'redirect_uri': env.str('REDIRECT_URL'),
'grant_type': 'authorization_code',
'client_id': env.str('CLIENT_ID'),
'client_secret': env.str('CLIENT_SECRET')
}).json()
access_token = response.get('access_token')
token_type = response.get('token_type')
refresh_token = response.get('refresh_token')
expires_in = response.get('expires_in')

edit_user_token(request.session.session_key, refresh_token, access_token, expires_in, token_type)
return redirect('/')

问题在最后一行:

return redirect('/')

如果我从我的前端(端口3000)登录Spotify,重定向链接将带我到端口8000,因为重定向回调函数是在Django中设置的。

我在3000端口上的测试无法继续。

这个问题有什么解决办法吗?或者我需要总是做npm运行构建和测试一切只在端口8000?

问题是:http://127.0.0.1:8000 api-spotify/回调

你必须注册一个新的url在Spotify的测试端口:http://127.0.0.1:3000 api-spotify/回调

最新更新