5

This is my URLs.py:

url(r'^api-auth/', include('rest_framework.urls',
                               namespace='rest_framework')),

I have a form on my homepage where users can type a username and password. When the submit button is clicked, AngularJS sends a POST request to "api-auth/login/" with the user object (username and password):

$http.post("/api-auth/login/", self.loginuser)
    .error(function(data, status, headers, config) {
        console.log(data);
     });

When a user submits an incorrect username and password (username and password which either do not exist or do not match), Django Rest Framework returns a 200 OK rather than a 204 No Content, 404 or 401 Unauthorized (on this post, it says 401 is the correct status code to return: What's the appropriate HTTP status code to return if a user tries logging in with an incorrect username / password, but correct format?).

According to here: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html in section 9.5 POST, it says "In this case, either 200 (OK) or 204 (No Content) is the appropriate response status, depending on whether or not the response includes an entity that describes the result."

I handle errors and log the data if data exists (I did console.log(data) in JS), but no data is logged, which means (from my understanding) no data is sent / the response does not include an entity that describes the result.

So how come DjangoRestFramework returns a 200 rather than a 204 No Content (or a 404 or 401, which is what should be returned according to the other SO post I linked to)?

4

3 回答 3

6
于 2015-10-01T22:26:54.933 回答
4

In my humble opinion, you are mixing business concepts with protocol issues here.

A login method should not return 401 (unauthorized) because it's prerequisite is that the user is (obviously) not yet authorized/authenticated. So if the request is made in a correct way (syntactically speaking), despite of the user credentials are incorrect (business concept), the response should be 200 (protocol), i.e., the request was accepted and properly processed. And of course, the response body will determine whether it was a successfull login or not.

So, after all, you are trying to log an application error when it is actually a business layer error (the user entered incorrect values according to your database). Get it?

于 2015-09-28T17:39:31.350 回答
2

If you look at DRF's source you will see that it uses Django's own Login/Logout views. Therefore this is question would be more related to Django's form handling itself. Here's a question that's related to Django itself.

于 2015-09-28T12:42:43.453 回答