简体   繁体   中英

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 ?

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));

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