【发布时间】:2021-04-06 07:05:43
【问题描述】:
这是一个不同的问题。我已经尝试研究这些信息几个小时了,但我似乎找不到我要找的东西。
我设置了一个 Django REST 后端。它非常简单的 REST API,只有一个模型
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 界面发帖,见下图
我想让 Django 服务器在后台运行,同时我创建一个前端,其文件(index.html、main.css、app.js 等...)与 django 项目是分开的。
然后我会使用Axios 获取,使用以下网址将数据发布到数据库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 项目中才能工作?
【问题讨论】:
标签: javascript python django rest