0

I am trying to send input fields' data to back end using fetch. I used formData.append to combine the data. when the fetch runs on backend I am getting empty list.

async function autosave()
{
    let formdata =new FormData();
    let blogImage = document.querySelector("#blog_image").files[0];
    let imageName = document.querySelector("#blog_image").files[0].name;
    let blogTitle = blog_title.value.trim();
    let contentType = document.querySelector("#content_type").checked;
    let blogId = document.querySelector("#id_val").value;
    let blogContent = editorbody.innerHTML;


    // console.log(document.querySelector("#blog_image").files[0])
    formdata.append("blog_image", blogImage, imageName)
    formdata.append("blog_title", blogTitle);
    formdata.append("content_type", contentType)
    formdata.append("blog_id", blogId);
    formdata.append("content",blogContent)
    await fetch("/blog/autosave/",{
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'mode':'no-cors'
        },
        method: "POST",
        body:JSON.stringify(formdata)
    }).then((res) => {return res.json()})
    .then((data) => {
        if (data.status == 200){
            // function savesuccessFun();
            console.log("Blog saved successfully");
        }
        else{
            // savefailFun();
             console.log("Opps blog can not be saved");
        }
    }).catch(err => console.log(err)); 

I know only front end. at back end we are getting data using data = json.loads(request.body)

NOTE: I mage should not be send in base64 format. All variables are taking data from form fields.

  • 1
    You can't correctly send formData like json body in post request, it has its own Content-Type etc (https://stackoverflow.com/questions/46640024/how-do-i-post-form-data-with-fetch-api). And also you need to read it differently in your backend, something like https://stackoverflow.com/questions/4706255/how-to-get-value-from-form-field-in-django-framework – Nikolay Jan 12 '23 at 06:55
  • Please refer to this answer https://stackoverflow.com/a/46640744/18265107 Also, it would really help if you could show us your backend code too. Are you using express for the backend? If yes then have you written this line before initializing all your routes - `app.use(express.urlencoded({ extended: true })` – Kshipra Jadav Jan 12 '23 at 05:39
  • we are using python django and we are retrieving data using data = json.loads(request.body) – Sampat Lal Aheer Jan 12 '23 at 06:40

0 Answers0