簡體   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