Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Posting data to django rest framework using javascript fetch

I'm trying to post data to my django rest framework using javascript fetch. I've already set up and liked the DRF to my model and got everything set up from the backend. I used the postman app to ensure "get", "post" etc are all working as interned. However, now I'm having problem posting data using javascript to post the data using fetch. I want to add data to my article model which has a "headline", "tag", "content", "background_image" and the user that posted the article.

This is how my code looks like

data = JSON.stringify({
    headline: "Testing",
    tag: "Testing",
    background_image: "Testing",
    content: "Testing",
    user: 1
})
fetch(
            "http://127.0.0.1:8000/api/v1/articlesapi/",
            {
                method: "post",
                headers: {"Authorization":"Token ed73db9bf18f3c3067be926d5ab64cec9bcb9c5e"},
                body: data
            }
 ).then(function(response) {
    return response.json();
}).then(function(data) {
    console.log("Data is ok", data);
}).catch(function(ex) {
    console.log("parsing failed", ex);
})

However, I keep getting the error parsing failed TypeError: Failed to fetch. Does anybody know what I'm doing wrong ?

like image 213
alpha787 Avatar asked Oct 29 '22 04:10

alpha787


1 Answers

Please add "Content Type" and "Accept" properties in your header, I think it could be a reason of your error. Let me know if it works :-)

fetch('"http://127.0.0.1:8000/api/v1/articlesapi/', {
      method: 'post',
      headers: {
        'Accept': 'application/json, text/plain, */*',
        'Content-Type': 'application/json',
        'Authorization':'Token ed73db9bf18f3c3067be926d5ab64cec9bcb9c5e'
      },
      body: JSON.stringify({data: "your data"})
    }).then(res=>res.json())
      .then(res => console.log(res));
like image 168
Karol Bilicki Avatar answered Nov 09 '22 22:11

Karol Bilicki