axios发送post请求时怎么自动携带cookie ,服务端django怎么接收
时间: 2023-12-03 20:42:12 浏览: 43
在axios发送post请求时,可以通过设置`withCredentials`为`true`来自动携带cookie:
```javascript
axios.post('/api/your-url', data, {
withCredentials: true
})
```
在服务端Django中,需要在视图函数或中间件中设置CORS(跨域资源共享)头部,以允许跨域请求携带cookie。可以使用`django-cors-headers`第三方库来实现。安装该库:
```
pip install django-cors-headers
```
在Django的`settings.py`中添加`corsheaders`应用,并设置`CORS_ORIGIN_ALLOW_ALL`为`True`,表示允许来自所有源的跨域请求:
```python
INSTALLED_APPS = [
# ...
'corsheaders',
# ...
]
MIDDLEWARE = [
# ...
'corsheaders.middleware.CorsMiddleware',
# ...
]
CORS_ORIGIN_ALLOW_ALL = True
```
这样,当客户端发送带有cookie的跨域请求时,服务端就可以接收到cookie了。在视图函数中,可以通过`request.COOKIES`来获取cookie:
```python
def your_view(request):
cookie = request.COOKIES.get('cookie_name')
# do something with the cookie
# ...
return JsonResponse({'success': True})
```