0

So the problem is I am trying to access the backend of my application but it is getting blocked by the above message. It works for 4-5 requested once I restart my server. But after that, its requests are getting added to the pending list. I am using react for the frontend and node js with PostgreSQL for the backend. I am not sure why this problem is happening with the website.

error-msg :

Access to XMLHttpRequest at 'https://athrv-ed-demo.herokuapp.com/events' from origin 'https://arthv-ed-demo.netlify.app' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Backend server code:

require("dotenv").config();
const express = require("express");
const app = express();
const cors = require("cors");
const port = process.env.PORT || 5000;
const routes = require("./routes");
const bodyParser = require("body-parser");
//middlewares
app.use(cors());
app.use(express.json());
app.use(require("morgan")("dev"));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.use(function (req, res, next) {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader(
    "Access-Control-Allow-Methods",
    "GET, POST, OPTIONS, PUT, PATCH, DELETE"
  );
  res.setHeader("Access-Control-Allow-Credentials", true);
  next();
});

//running the express app here
app.use("/", routes);

app.listen(port, () => {
  console.log(`My app is running at ${port}`);
});

Here is the front-end code from where I am making the calls. The same thing is happening with both API.

const axios = require("axios");

const url = "http://localhost:5000";
// const url = "https://athrv-ed-demo.herokuapp.com";

export async function getevents() {
  console.log("Preload triggered at index");
  return await axios({
    url: `${url}/events`,
    method: "GET",
    headers: {
      mode: "no-cors",
      Accept: "application/json",
    },
  })
    .then((response) => {
      // console.log("events recieved, From axios");
      // console.logponse.data);
      return response.data;
    })
    .catch((err) => {
      // console.log("events not recieved, error in axios" + err);
      return false;
    });
}

export async function eventedit(event) {
  // console.log("edit event is clicked");
  return await axios({
    url: `${url}/eventedit/${isAuthenticated().user.uid}/${event.eid}`,
    method: "PUT",
    headers: {
      mode: "no-cors",
      Accept: "application/json",
      Authorization: `Bearer ${isAuthenticated().token}`,
    },
  })
    .then((response) => {
      // console.log("view toggled !, From axios");
      // console.log(response.data);
      return response.data;
    })
    .catch((err) => {
      // console.log("view couldn't be toggled, error in axios" + err);
      return false;
    });
}

export async function getlist(event) {
  return await axios({
    url: `${url}/getlist/${isAuthenticated().user.uid}/${event.eventno}`,
    method: "GET",
    headers: {
      mode: "no-cors",
      Accept: "application/json",
      Authorization: `Bearer ${isAuthenticated().token}`,
    },
  })
    .then((response) => {
      // console.log("got all peoples !, From axios");
      // console.log(response.data);
      return response.data;
    })
    .catch((err) => {
      console.log("couldn't get all people, error in axios" + err);
      return false;
    });
}

export async function register(user) {
  return await axios({
    url: `${url}/registration`,
    method: "POST",
    data: {
      name: user.name,
      age: user.age,
      phone: user.phone,
      email: user.email,
      college: user.college,
      eventno: user.eventno,
    },
    headers: {
      mode: "no-cors",
      Accept: "application/json",
      "Content-Type": "application/json",
    },
  })
    .then((response) => {
      // console.log("registration done!, From axios");
      // console.log(response.data);
      return response.data;
    })
    .catch((err) => {
      // console.log("registration not done, error in axios" + err);
      return false;
    });
}

export async function signin(user) {
  return await axios({
    url: `${url}/signin`,
    method: "POST",
    data: {
      email: user.email,
      password: user.password,
    },
    headers: {
      mode: "no-cors",
      Accept: "application/json",
      "Content-Type": "application/json",
    },
  })
    .then((response) => {
      // console.log("data from axios and signin successfull ");
      // console.log(response.data);
      return response.data;
    })
    .catch((err) => {
      // console.log(user.password + " " + user.email);
      // console.log("Error in axios {email and password doesn't match}");
      return false;
    });
}

export const signout = () => {
  if (typeof window !== "undefined") {
    localStorage.removeItem("jwt");

    return axios({
      url: `${url}/signout`,
      method: "GET",
    })
      .then((response) => {
        console.log("Signout Successfull from Axios");
      })
      .catch((err) => {
        console.log(err);
      });
  }
};

export async function postevent(event) {
  return await axios({
    url: `${url}/postevent/${isAuthenticated().user.uid}`,
    method: "POST",
    data: {
      name: event.name,
      date: event.date,
    },
    headers: {
      mode: "no-cors",
      Accept: "application/json",
      Authorization: `Bearer ${isAuthenticated().token}`,
    },
  })
    .then((response) => {
      // console.log("new event posted!, From axios");
      // console.log(response.data);
      return response.data;
    })
    .catch((err) => {
      // console.log("Couldn't post, error in axios" + err);
      return false;
    });
}

export const authenticate = (data, next) => {
  if (typeof window !== "undefined") {
    localStorage.setItem("jwt", JSON.stringify(data));
    next();
  }
};

export const isAuthenticated = () => {
  if (typeof window == "undefined") {
    return false;
  }
  if (localStorage.getItem("jwt")) {
    return JSON.parse(localStorage.getItem("jwt"));
  } else {
    return false;
  }
};

Avinash Kumar
  • 71
  • 1
  • 5
  • It's good idea to see [this](https://stackoverflow.com/a/43268098/1706467) answer at first. – Navand Mar 03 '21 at 07:19
  • I have checked that but my problem is a little different. It is working where I restart the server, but after a certain number of requests, it stops working – Avinash Kumar Mar 03 '21 at 10:23

0 Answers0