【问题标题】:Posting data to django rest framework using javascript fetch使用 javascript fetch 将数据发布到 django rest 框架
【发布时间】:2017-12-31 15:59:48
【问题描述】:

我正在尝试使用 javascript fetch 将数据发布到我的 django rest 框架。我已经为我的模型设置并喜欢了 DRF,并从后端设置了所有内容。我使用邮递员应用程序来确保“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。有谁知道我做错了什么?

【问题讨论】:

    标签: javascript django rest api django-rest-framework


    【解决方案1】:

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

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

    【讨论】:

    • 刚刚这样做并得到以下错误Uncaught (in promise) TypeError: Failed to fetch
    • hmm 尝试在标题中使用 "Content-Type": "text/plain"。
    • 是的,这似乎已经解决了。感谢您的帮助队友
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-25
    • 1970-01-01
    • 2014-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多