This is a bit of a different question. I’ve tried researching the information for a few hours now and I can’t seem to find what I am looking for.
I have a Django REST backend that I set up. Its very simple REST API that has one 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
I’m able to post to via the REST api interface see image below
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.
I would then use Axios
to GET, POST data to the database using the following url http://127.0.0.1:8000/api/heroes/
Below is the code from my front end
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); }); } }
However I am getting a CROS error
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.
How can I submit data from my front end app to my back end app without having this issue?
Do my frontend files need to be in my django project for it to work?
Advertisement
Answer
No matter where you put your front end files, both are served from different servers. so you need to use https://github.com/adamchainz/django-cors-headers in your back end.