从前端分离Django支架背面

2024-05-18 14:31:12 发布

您现在位置:Python中文网/ 问答频道 /正文

这是一个有点不同的问题。我已经试着研究了几个小时的信息,但我似乎找不到我要找的东西

我设置了一个Django REST后端。它的RESTAPI非常简单,只有一个模型

Model.py

from django.db import models

# Create your models here.
class Hero(models.Model):
  name = models.CharField(max_length=60)
  alias = models.CharField(max_length=60)

  def __str__(self):
    return self.name

我可以通过RESTAPI接口发布到,请参见下图

enter image description here

我希望Django服务器在后台运行,同时创建一个前端,其文件(index.html、main.css、app.js等)与Django项目分开

然后,我将使用Axios获取数据,并使用以下url http://127.0.0.1:8000/api/heroes/将数据发布到数据库

下面是我前端的代码

import axios from "axios";

export default class SuperHero {
  constructor() {
    this.superHeroForm = document.querySelector("#superHeroForm");
    this.events();
  }

  events() {
    this.superHeroForm.addEventListener("submit", e => this.onSubmit(e));
  }

  onSubmit(e) {
    e.preventDefault();
    console.log("onSubmit ran");
    this.name = document.querySelector("#name").value;
    this.alias = document.querySelector("#alias").value;

    axios
      .post("http://127.0.0.1:8000/api/heroes/", {
        name: this.name,
        alias: this.alias
      })
      .then(res => {
        console.log(res);
      })
      .catch(e => {
        console.log(e);
      });
  }
}

然而,我得到了一个CROS错误

Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/heroes/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

如何在没有此问题的情况下将数据从前端应用提交到后端应用

我的前端文件需要在django项目中才能工作吗


Tags: djangonamefromapihttpmodelsaliasthis

热门问题