Fetch 方法 put 给出“SyntaxError: Unexpected end of JSON input”

时间:2021-02-21 13:07:42

标签: javascript json django fetch

我声明脚本有效:成功地将正确的字段更改为正确的值。尽管如此,我还是收到了这个错误“SyntaxError: Unexpected end of JSON input”。

这是客户端js代码。该函数获取广告 'id' 、要更改的字段和值:

function mark(id,field,yesno){
  fetch('/emails/'+id,{
    method : 'PUT',
    headers: {'Content-Type': 'application/json'},
    body : JSON.stringify({
      [field]:yesno
    })
  })
  .then(response =>response.json())
  .catch(error => {console.log('Error while processing the request:' , error)})
}

views.py 上的一段代码

...
 elif request.method == "PUT":
        data = json.loads(request.body)
        if data.get("read") is not None:
            email.read = data["read"]
        if data.get("archived") is not None:
            email.archived = data["archived"]
        email.save()
        return HttpResponse(status=204)
...

还有models.py

class Email(models.Model):
    user = models.ForeignKey("User", on_delete=models.CASCADE, related_name="emails")
    sender = models.ForeignKey("User", on_delete=models.PROTECT, related_name="emails_sent")
    recipients = models.ManyToManyField("User", related_name="emails_received")
    subject = models.CharField(max_length=255)
    body = models.TextField(blank=True)
    timestamp = models.DateTimeField(auto_now_add=True)
    read = models.BooleanField(default=False)
    archived = models.BooleanField(default=False)

    def serialize(self):
        return {
            "id": self.id,
            "sender": self.sender.email,
            "recipients": [user.email for user in self.recipients.all()],
            "subject": self.subject,
            "body": self.body,
            "timestamp": self.timestamp.strftime("%b %d %Y, %I:%M %p"),
            "read": self.read,
            "archived": self.archived
        }

0 个答案:

没有答案