在使用axios向后端发送POST请求的时候,服务器无法得到POST中带有的参数。
前端的发送代码如下:
Http({
method:'POST',
url:'signup',
data:{
username:this.signUpform.username,
password:this.signUpform.password,
email:this.signUpform.email,
cellphone:this.signUpform.cellphone
}
})
Axios设置如下:
import axios from 'axios'
export default axios.create({
baseURL: 'http://127.0.0.1:8000/api',
timeout: 20000,
headers: {'Content-Type': 'application/json'}
})
后台接受代码如下:
@require_http_methods(["POST"])
def signup(request):
response = {}
try:
print(request.POST.get('username'))
WorkUser.objects.get(username=request.POST.get('username'))
response['error'] = 'username already exist'
except WorkUser.DoesNotExist:
wu=tools.toWorkUser(request)
wu.save()
response['error'] = 'success'
return JsonResponse(response)
输出,显示:
None
Internal Server Error: /api/signup
Traceback (most recent call last):
File "C:\Users\fengfanfan\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\datastructures.py", line 77, in __getitem__
list_ = super().__getitem__(key)
KeyError: 'username'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\fengfanfan\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\exception.py", line 35, in inner
response = get_response(request)
File "C:\Users\fengfanfan\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\fengfanfan\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\fengfanfan\AppData\Local\Programs\Python\Python36\lib\site-packages\django\views\decorators\http.py", line 40, in inner
return func(request, *args, **kwargs)
File "E:\WorkSpace\GraduationThesis\GPServer\server\views.py", line 36, in signup
WorkUser.objects.get(username=request.POST['username'])
File "C:\Users\fengfanfan\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\datastructures.py", line 79, in __getitem__
raise MultiValueDictKeyError(key)
django.utils.datastructures.MultiValueDictKeyError: 'username'
然而,使用Postman接口却可以使用,这是为什么呢
终于找到可以用的办法了,似乎只要在前端对data处理一下就可以了,用qs: