我构建了一个API usign 2和Django Rest框架。所有get方法都是正常的,首先使用身份验证来接收令牌,然后使用此令牌访问所有其他方法。唯一的问题是,我所拥有的唯一接收POST数据的功能。
问题是,对POST方法的调用总是返回,甚至提供“授权”令牌,这个消息:
“{”详细信息“:”未提供身份验证凭据“}
有趣的是,在邮递员中,它是有效的!另一个开发人员尝试使用JavaScript,它总是返回这条消息。我尝试使用PHP使用CURL发出POST请求,并给出相同的错误。就和邮递员一起工作..。
这是我在settings.py中的Django Rest框架设置:
INSTALLED_APPS = [
...
'rest_framework.authtoken',
...
]
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
),
}在views.py中,这是一种名为the的方法:
@api_view(['POST'])
def api_inventory_sector_items_check(request, branch_id, inventory_id, sector_id):
# Do something这是url.py:
# ...
from rest_framework.urlpatterns import format_suffix_patterns
# ...
urlpatterns = [
...
path('.../check', # See the long URL bellow
views.api_inventory_sector_items_check,
name='app.api.inventory_sector_items_check'),
]
# ...所以我试着用POST打电话:
{{domain}}/app/api/v1/branches/1/inventories/2/sectors/100101329/items/check “内容-类型:应用程序/json” “授权:令牌efad3303547374b7c035499218ad5d0cceb03178”
在身体上发布一些数据..。
就像我之前说过的,用邮递员没关系。但是当我们试图通过任何其他的“方法”提交这个帖子时,它会返回相同的消息。细节:具有相同的标题,但对于GET请求,所有工作。
遵循一个使用PHP返回“.凭据未提供”的请求示例。
<?php
$data = array(
"data"=>"{'id':'20012738', 'obs': '', 'resp':'325880','final':1}",
);
$data_string = json_encode($data);
$ch =
curl_init('http://localhost/app/api/v1/branches/1/
inventories/7/sectors/100162162/items/check');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string)),
'Authorization: Token efad3303547374b7c035499218ad5d0cceb03178'
);
$result = curl_exec($ch);
echo $result;
?>有人能帮我吗?非常感谢!
发布于 2018-04-13 10:33:50
您有一个微妙的错误:
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string)),
'Authorization: Token efad3303547374b7c035499218ad5d0cceb03178'
); array()在添加Authorization头之前结束(请注意内容长度标题末尾的结束括号)。这将阻止令牌被正确传输,并可能导致身份验证错误。
改为:
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string),
'Authorization: Token efad3303547374b7c035499218ad5d0cceb03178')
); 发布于 2018-04-13 16:24:43
我的PHP代码提交是错误的,并将帮助我。谢谢。无论如何,提交Django Rest的POST数据没有数据.我用以下方法解决了这个问题:
request.body相反,
request.POST.get('data')然后,我的代码变成这样:
@api_view(['POST'])
def api_inventory_sector_items_check(request, branch_id, inventory_id, sector_id):
try:
sector_items = request.body
except Exception:
return Response({"detail": "No data received or isn't a JSON data"}, status=status.HTTP_406_NOT_ACCEPTABLE)
try:
sector_items = json.loads(sector_items)
except json.JSONDecodeError or TypeError:
return Response({
'detail': "Data received has a wrong format. This is not a JSON var."
}, status=status.HTTP_404_BAD_REQUEST)https://stackoverflow.com/questions/49801089
复制相似问题