Posting data to django rest framework using javascript fetch -
i'm trying post data django rest framework using javascript fetch. i've set , liked drf model , got set backend. used postman app ensure "get", "post" etc working interned. however, i'm having problem posting data using javascript post data using fetch. want add data article model has "headline", "tag", "content", "background_image" , user posted article.
this how code looks
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 ok", data); }).catch(function(ex) { console.log("parsing failed", ex); })
however, keep getting error parsing failed typeerror: failed fetch
. know i'm doing wrong ?
please add "content type" , "accept" properties in header, think reason of error. let me know if 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));
Comments
Post a Comment