出现这个问题是因为没有搞清楚 Django 中获取表单数据和字符串数据的两种方式。下面我们就来梳理下 Django 的接收值的方式和 vue 的传值方式。
在 Django 中,你可以通过 request.POST
来获取这些数据
| def my_view(request): |
| if request.method == 'POST': |
| key1 = request.POST.get('key1') |
| key2 = request.POST.get('key2') |
| |
在 Django 中,你可以通过 request.body
来获取这些数据,并使用 json.loads
方法将其解析为 Python 字典
| import json |
| |
| def my_view(request): |
| if request.method == 'POST': |
| data = json.loads(request.body) |
| username = data.get('username') |
| password = data.get('password') |
| |
| # 打印request.body是下面的数据 |
| b'{"username":"zhangsan","password":"111"}' |
这种形式的数据,应该是最常见的。一般在前端,我们都是将参数以 json 的形式传到后端。
| import axios from 'axios'; |
| |
| const formData = { |
| 'username': form.value.username, |
| 'password': form.value.password, |
| }; |
| |
| axios.post('http://your-django-api-url.com/endpoint/', formData) |
| .then(response => { |
| console.log(response.data); |
| }) |
| .catch(error => { |
| console.error(error); |
| }); |
axios 中默认的 content-type 是 application/json;charset=utf-8
, 这样数据将会以 json 的格式传到后端
要在 Vue 中使用 Axios 发送表单数据,并通过设置请求头的方式通知 Django 接收到的数据是表单数据,需要使用 Content-Type
头部来指定数据格式为 application/x-www-form-urlencoded
| import axios from 'axios'; |
| |
| |
| const formData = new URLSearchParams(); |
| formData.append('username', form.value.username); |
| formData.append('password', form.value.password); |
| |
| |
| axios.post('http://your-django-api-url.com/endpoint/', formData, { |
| headers: { |
| 'Content-Type': 'application/x-www-form-urlencoded' |
| } |
| }) |
| .then(response => { |
| console.log(response.data); |
| }) |
| .catch(error => { |
| console.error(error); |
| }); |
首先创建了一个 URLSearchParams
对象 formData,并使用 append 方法向其中添加了键值对。然后,在发送 POST 请求时,我们通过 headers 选项设置了 Content-Type
头部为 application/x-www-form-urlencoded
,这样 Django 就会知道接收到的数据是表单数据。
顺便这里总结下常见的三种 Content-Type 头部设置
| |
| 'Content-Type: application/json' |
| |
| 'Content-Type: application/x-www-form-urlencoded' |
| |
| 'Content-Type: multipart/form-data' |