5

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 ?

0

1 Answer 1

3

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));
Sign up to request clarification or add additional context in comments.

3 Comments

Just did that and got the following error Uncaught (in promise) TypeError: Failed to fetch
hmm try with "Content-Type": "text/plain" in header.
Yep, that seems to have fixed it. Thanks for your help mate

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.