简体   繁体   中英

What's wrong with my tastypie POST request?

I'm getting a 401 when trying to do a post in ajax with Tastypie. I can log a GET to the console, and they use the same authentication. How can I debug?

Here's my javascript:

// sending a csrftoken with every ajax request
function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    crossDomain: true, // obviates need for sameOrigin test
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type)) {
            xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken'));
        }
    }
});

//this is the get request, which works fine
$.ajax({
   url: "http://localhost:8080/data/api/v1/user/?format=json",
   success: function(data){
console.log(data);
}
});

$(function() {
  $('#newEntry').click(function() {
   var table=$("#entryName").val(); 
   var d = JSON.stringify({
    "name":entry,
    "user":"http://localhost:8080/data/api/v1/user/?format=json"
    });

    $.ajax({
      type: 'POST',
      data: d,
      success: function(r) {console.log(r); },
      error: function(r){console.log(r); },
      url: 'http://localhost:8080/data/api/v1/entry/',
      cache:false
    });
  });
});

I asked this question earlier, as I thought it would help, but it hasn't. It has more context, namely about what I'm using for auth, but I can provide more detail if needed.

401 usually means you aren't authorized to access that resource, or there is a CSRF issue.

Two things spring to mind

  1. You are not authenticated. Are you logged in( SessionAuthentication ), or are you sending the username and api key with your request( ApiKeyAuthentication ).

  2. If #1 is not the problem, then maybe it's because the csrf token has not been set. Django does not set the token for all requests. From the docs -

If your view is not rendering a template containing the csrf_token template tag, Django might not set the CSRF token cookie. This is common in cases where forms are dynamically added to the page. To address this case, Django provides a view decorator which forces setting of the cookie: ensure_csrf_cookie() .

I'm guessing that #2 is the more like scenario. You can either wrap your views in the ensure_csrf_cookie decorator, or use a middleware to do that for all requests. Or you could use the api key for authentication, as it does not look like it checks for csrf token(not really sure, but I'm looking at the tastypie code and I don't see any csrf checks.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM