繁体   English   中英

从前端分离 Django REST

[英]Separating Django REST back from Front end

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

我有一个我设置的 Django REST 后端。 它非常简单的 REST API 有一个 Model

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

我可以通过 REST api 界面发帖,见下图

在此处输入图像描述

I'd like to have the Django server running in the background while I create a front end whose files (index.html, main.css, app.js ect....) are separate from the django project.

然后,我将使用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 项目中才能正常工作?

无论您将前端文件放在哪里,两者都来自不同的服务器。 所以你需要在后端使用https://github.com/adamchainz/django-cors-headers

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM