请求正文在django中是空的

时间:2017-10-08 06:01:45

标签: python django reactjs

我正在使用创建反应应用程序前端。我的问题是每个POST请求都不包含任何来自django方面。以下是观点:

def login(request):
    if request.method == "POST":
        username = request.POST.get('username')
        password = request.POST.get('password')
        print(request.POST) // prints <QueryDict: {}>
        user = auth.authenticate(username=username, password=password)
        if user:
            token = Token.objects.get_or_create(user=user)
            return JsonResponse({'token': str(token[0])}, status=status.HTTP_200_OK)
        else:
            return JsonResponse({'error': 'Username/Password is not valid'}, status=status.HTTP_401_UNAUTHORIZED)

我已经在package.json中添加了"proxy": "http://localhost:8000"

以下是反应部分:

handleSubmit(event) {
        event.preventDefault();
        axios({
            method: "post",
            url: "/api/auth/",
            data : {
                "username": this.state.username,
                "password": this.state.password
            }
        }).then(function (response) {
            console.log(response);
        }).catch(function(error){
            console.error(error.response.data["error"]);
        })
    }

我还检查了前端网络数据,请求体中有用户名和密码。

urls.py

router = routers.DefaultRouter()
router.register(r'notes', views.NotesViewset)

urlpatterns = [
    url(r'^api/auth/', views.login),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
    url(r'^api/', include(router.urls)),
    url(r'^', views.BunnyAppView.as_view()),
]

2 个答案:

答案 0 :(得分:2)

您将获得request.data中的数据,request.POST用于表单编码数据。

但是如果你想要request.POST QueryDict中的数据,你需要对数据进行编码。

  

axios默认内容类型为application/json

axios支持URLSearchParams,可用于从浏览器以application/x-www-form-urlencoded发送数据:

var params = new URLSearchParams();
params.append('username', this.state.username);
params.append('password', this.state.password);

axios({
      method: "post",
      url: "/api/auth/",
      data : params
})

或者您可以使用qs

等库对数据进行编码
var qs = require('qs');
axios.post('/foo', qs.stringify({ 'bar': 123 });

答案 1 :(得分:1)

在axios和django中出现此问题。为防止请求主体为空,应使用self.request.data。 这是整个工作解决方案:

axios:

axios.defaults.headers = {
    "Accept": "application/json",
    "Content-Type": "application/json",
    "Authorization": "Token " + this.props.token
}
axios.post('http://127.0.0.1:8000/categoryCreate/', {
    name: name,
})
.then(res => {

})

views.py

class CategoryCreateAPIView(generics.CreateAPIView):
    serializer_class = CategoryCreateSerializer

    def perform_create(self, serializer):
        print(self.request.data)
        name = self.request.data["name"]
        print(name)
        serializer.save(name=name, user=self.request.user)

serializers.py

class CategoryCreateSerializer(serializers.ModelSerializer):
    name = serializers.CharField()

    class Meta:
        model = Flokkur
        fields = ('name', )

urls.py:

path('categoryCreate/', CategoryCreateAPIView.as_view()),