我正在嘗試驗證所需的資料是否包含在 POST 請求中。我有一個django后端和一個vue3前端。
這是我的 Django 視圖:
views.py
# Sign user in and issue token
@require_http_methods(['POST'])
def login(request: HttpRequest):
if request.method == 'POST':
# check that required fields were send with POST
print(request.body)
if {'username', 'password'} >= set(request.POST): # <- evaluates as False
print('missing required fields. INCLUDED: ' str(request.POST))
return JsonResponse(
data={'message': 'Please provide all required fields.'},
content_type='application/json',
status=400)
# check that username exists and password matches
if (User.objects.filter(username=request.POST['username']).count() >
0):
user = User.objects.get(username=request.POST['username'])
if user.password == request.POST['password']:
# Delete previously issued tokens
Token.objects.filter(user_id=user.id).delete()
token = Token(user_id=user.id)
token.save()
return JsonResponse(data={'userToken': token.to_json()},
content_type='application/json',
status=200)
else:
return JsonResponse(
data={'message': 'Incorrect username or password.'},
content_type='application/json',
status=400)
else:
return HttpResponseNotAllowed(permitted_methods=['POST'])
還有我的 axios 請求
Login.vue
axios
.post('http://localhost:8000/api/users/login', {
'username': form.get('username'),
'password': form.get('password'),
}, {
validateStatus: (status) => {
return status !== 500
},
})
.then((response) => {
console.log(response.data)
if (response.data.success) {
// Commit token value to store
store.commit('setToken', response.data.token)
// Request user data ...
} else {
alert.message = response.data.message
alert.type = 'error'
document.querySelector('#alert')?.scrollIntoView()
}
})
我可以看到username并password設定了request.body但不像request.POSTdjango 日志中顯示的那樣。
December 01, 2021 - 17:40:29
Django version 3.2.9, using settings 'webserver.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
b'{"username":"site.admin","password":"password"}'
missing required fields. INCLUDED: <QueryDict: {}>
Bad Request: /api/users/login
[01/Dec/2021 17:40:30] "POST /api/users/login HTTP/1.1" 400 50
/Users/colby/Projects/emotions/backend/webserver/users/views.py changed, reloading.
Watching for file changes with StatReloader
Performing system checks...
我做錯了什么?
編輯
這是從 axios 請求中設定的標頭
{
'Content-Length': '47',
'Content-Type': 'application/json',
'Host': 'localhost:8000',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; rv:91.0) Gecko/20100101 Firefox/91.0',
'Accept': 'application/json,
text/plain, */*',
'Accept-Language': 'en-US,en;q=0.5',
'Accept-Encoding': 'gzip, deflate',
'Origin': 'http://localhost:8080',
'Dnt': '1',
'Connection': 'keep-alive',
'Referer': 'http://localhost:8080/',
'Sec-Fetch-Dest': 'empty',
'Sec-Fetch-Mode': 'cors',
'Sec-Fetch-Site': 'cross-site',
'Sec-Gpc': '1'
}
編輯 2
我能夠通過將 Content-Type 標頭顯式設定為multipart/form-data.
axios
.post('http://localhost:8000/api/users/login', formData,
{
validateStatus: (status) => {
return status !== 500
},
headers: {
'Content-Type': 'multipart/form-data',
}
).then(...)
我還必須將 Django 視圖中的 if 陳述句調整為
if 'username' not in request.POST or 'password' not in request.POST:
...
uj5u.com熱心網友回復:
我懷疑 Axios 正在自動設定一個content-type: application/json標頭,這意味著請求正文不包含 Django 可以理解的 HTTP POST 引數。
您可以通過列印來驗證這一點request.headers,如果這確實是問題,請通過以下任一方式解決:
- 從 JSON 決議請求正文:
import json
data = json.loads(response.body.decode())
if {'username', 'password'} >= set(data): # etc.
- 將資料作為表單資料客戶端發送:
var formData = new FormData();
formData.append("username", form.get("username"))
formData.append("password", form.get("password"))
axios
.post('http://localhost:8000/api/users/login',
formData,
{headers: {'Content-Type': 'multipart/form-data'}
})
我個人推薦解決方案 1,因為我發現它不那么冗長且易于維護,但這主要取決于您的偏好和要求:)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/371711.html
上一篇:在Django中按天分組文章
