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

alp*_*787 5 javascript api django rest django-rest-framework

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

这是我的代码的样子

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);
})
Run Code Online (Sandbox Code Playgroud)

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

Kar*_*cki 3

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

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));
Run Code Online (Sandbox Code Playgroud)