如何在Django中读取Axios POST请求的Headers?代码问题排查
问题分析与解决方案
1. Axios请求参数结构错误
你当前的Axios POST请求把headers和params都放在了第二个参数(请求体位置),但Axios的正确语法是:
axios.post(url, requestBody, config)
headers和params属于配置项,应该放在第三个参数里,而非请求体中——这直接导致后端无法从请求头中读取到Authorization字段。
修正后的前端代码:
async function sendBookingRequest() { try { axios.post( "https://danilo2588.pythonanywhere.com/book", {}, // 若无需请求体数据则留空 { headers: {'Authorization':"1234567890123456789012345678901234567890"}, params:{ 'requested_date':date, 'hours':bookedHours, 'business':cancha, 'phone':cellphone, } } ) .then( function(response){ setConfirmation(response.data) setStepper(7) }) .finally(() => { setIsLoading(false) }) } catch(error){ console.log(error) }; }
额外注意:finally里的代码要包裹在箭头函数中,否则会在请求发起时立即执行,而非请求完成后执行。
2. 跨域(CORS)配置问题
如果前端和后端属于不同域名,浏览器会触发跨域检查,默认拦截自定义请求头(比如Authorization)。需要在Django中配置CORS允许该头:
- 确保安装
django-cors-headers包 - 在
settings.py中添加如下配置:
INSTALLED_APPS = [ # ...其他应用 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', # ...其他中间件 ] # 生产环境建议指定具体域名,此处为测试用配置 CORS_ALLOW_ALL_ORIGINS = True # 允许携带Authorization头 CORS_ALLOW_HEADERS = ['Authorization', 'Content-Type']
3. 后端代码异常处理优化
当前后端代码若Token不存在会直接抛出错误,建议添加异常捕获避免崩溃:
from django.http import HttpResponseBadRequest from rest_framework.authtoken.models import Token def booking(request): auth_key = request.headers.get('Authorization') if auth_key: try: generic_user = Token.objects.get(key=auth_key).user except Token.DoesNotExist: return HttpResponseBadRequest("无效的认证密钥") if request.method == "POST" and generic_user: # 执行预约业务逻辑... else: return HttpResponseBadRequest("缺少认证头")
内容的提问来源于stack exchange,提问作者Adrian
相关产品推荐
相关产品推荐

