Search code examples
pythonreactjsdjangogoogle-chromedjango-cors-headers

Cors-erorr occurs when I send a post request, but corsheaders are configured


I want to make a post request for back end from front end, but I get an error in my browser. I tested it through postman - there are no problems with logic on the backend, and I have configured corsheaders correctly, I think. (frontend - Next.js) (backend - Django rest)

settings.py

CORS_ALLOWED_ORIGINS = [
    "http://localhost:3000",
    "http://127.0.0.1:3000",
]
CORS_ALLOW_ALL_ORIGINS = True

CORS_ORIGIN_WHITELIST = [
    "http://localhost:8000",
]
CORS_ALLOW_METHODS = [
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
]

here's my this post request from the front, couldn't seem to find any errors in it either

page.js

'use client'
import styles from "./page.module.css";
import axios from "axios";
import { useState } from "react";
export default function Home() {

  const [data, setData] = useState([]);
  const [postData, setPostData] = useState({
    password: "",
    message: "",
  });

  const handleSubmit = async (event) => {
    event.preventDefault();
    try{
      const res = await axios.post("http://127.0.0.1:8000/message-post/", postData, {
        headers : {
          'Content-Type': 'application/json'
        }
      });
      const data = res.data;
      setData(data);
    } catch(error){
      console.log(error);
    }
  }

  return (
    <div>
      {data.map((dat, index) => (
        <div key={index}>
            <a>{dat.message}</a>
        </div>
      ))}
        <form className={styles.formdata} method="POST" onSubmit={handleSubmit}>
          <div className={styles.input_fields}>
            <a className={styles.textupper}>Chatting anonymously</a>
            <input className={styles.password} type="text" placeholder="Enter password"
                value={postData.password} onChange={(e) => setPostData({...postData, password: e.target.value})}></input>

            <textarea className={styles.message} type="text" placeholder="Massage..." 
                value={postData.message} onChange={(e) => setPostData({...postData, message: e.target.value})}></textarea>
            <button className={styles.encrypt} type="submit">Encrypt message</button>
          </div>
        </form>
    </div>
  );
}

This shows this cors-error

The preflight request works fine, and the response shows that only POST and OPTIONS are available for this url


Solution

  • For cors to be included in your responses, you'll need to add it to your middlewares too. Considering you haven't added it, as it is not mentioned in the code snippets, You can follow the guide here: https://www.geeksforgeeks.org/how-to-enable-cors-headers-in-your-django-project/

    For reading further info on how CORS middleware works in django, you can go through the resources mentioned in this answer: https://stackoverflow.com/a/35761088/11539362