Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

javascript - Django CSRFToken middleware appends to URL and shows up after making a “PUT” request to the server. (AJAX issue)

I’m working on a Django Python/Javascript project. The PUT request is done through the client and sent back to the server. After sending the request successfully, the page makes a refresh which is causing the exposure of the csrf token middleware in the URL. I already implemented AJAX, returning false, added an event.preventDefault(), passed a cookie through the header of the fetch, used async functions, and added a try and catch syntax. And I can’t figure out why it is not affecting the resubmission. I need to stop the webpage from refreshing once the submission is done so that the csrf_token won't show appended to the URL.

Hopefully, someone can let me know what I’m not seeing here. Thanks!

// Set global variables to use in form submission
var id, upt_prodName, upt_prodPrice, upt_prodDescpt;

// Block to populate textarea that allows the user to update product info.
 
 const editProd_view = (response) => {
 
  let prod_id = response.id;
  let edit_name = response.name;
  let edit_price = response.price;
  let edit_descpt = response.description;
 
 
 let prod_idUpt = (document.querySelector("#prod_idUpt").innerHTML = prod_id);
 let new_name = (document.querySelector(
  "#editProdName"
   ).innerHTML = edit_name);
 let new_price = (document.querySelector(
  "#editProdPrice"
   ).innerHTML = edit_price);
 let new_textarea = (document.querySelector(
  "#editProdDescpt"
   ).innerHTML = edit_descpt);
 
 id = prod_id;
 
//On submit, send product info to update the product.

 const edit_prod = (document.querySelector(
  "#editProd_form").onsubmit = async () => {
     try {

// Get all values from textarea to update content.
     upt_prodName = document.getElementById("editProdName").value;
     new_prodPrice = document.getElementById("editProdPrice").value;
     new_prodDescpt = document.getElementById("editProdDescpt").value;
 
     const res = await fetch(
       `/editProduct/${id}`,
          {
    method: "PUT",
    headers: {
    "Content-Type": "application/json",
    "X-CSRFToken": getCookie("csrftoken"),
    },
    body: JSON.stringify({
      name: upt_prodName,
      description: upt_prodDescpt,
      price: upt_prodPrice,
     }),
    })
    .then((res) => res.json())
    .then((result) => {
console.log("result ->", result);
    });
} catch (err) {
  console.error("err", err);
}

//Once the post has been submitted, return false to prevent reloading.

 edit_prod.handleForm();
 return false;
 });

return false;
};


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yeah inside django for post and put, delete requires a csrf token, my solution

you can do this

<form>
 <button id="onsubmit" method="{{csrf_token}}">submit</button>
</form>

$(document).on(function() {
   $(document).on('click', '#onsubmit', function() {
      var token = $(this).attr("method")
      const res = await fetch(
       `/editProduct/${id}`,
          {
    method: "PUT",
    headers: {
    "Content-Type": "application/json",
    "X-CSRFToken": token,
    },
    body: JSON.stringify({
      name: upt_prodName,
      description: upt_prodDescpt,
      price: upt_prodPrice,
     }),
    })
    .then((res) => res.json())
    .then((result) => {
console.log("result ->", result);
    });
} catch (err) {
  console.error("err", err);
}
   })
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...