gpt4 book ai didi

javascript - 使用javascript fetch将数据发布到django rest框架

转载 作者:行者123 更新时间:2023-11-29 11:02:08 25 4
gpt4 key购买 nike

我正在尝试使用 javascript fetch 将数据发布到我的 django rest 框架。我已经为我的模型设置并喜欢 DRF,并从后端设置了所有内容。我使用 postman 应用程序来确保“get”、“post”等都像实习生一样工作。但是,现在我在使用 javascript 使用 fetch 发布数据时遇到问题。我想将数据添加到我的文章模型中,该模型具有“标题”、“标签”、“内容”、“背景图像”和发布文章的用户。

我的代码是这样的

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

但是,我不断收到错误 parsing failed TypeError: Failed to fetch。有人知道我做错了什么吗?

最佳答案

请在标题中添加“内容类型”和“接受”属性,我认为这可能是您出错的原因。让我知道它是否有效:-)

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

关于javascript - 使用javascript fetch将数据发布到django rest框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45308153/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com