Ashutosh Krishna
Ashutosh Krishna

Reputation: 330

How to set the cors policy in react frontend?

I am getting this error

My signup component looks like this :

import fetch from "isomorphic-fetch";
import { API } from "../config";
import cookie from "js-cookie";

export const signup = (user) => {
  return fetch(`${API}/signup`, {
    method: "POST",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
    },
    body: JSON.stringify(user),
  })
    .then((response) => {
      return response.json();
    })
    .catch((err) => console.log(err));
};

My Signup Controller looks like this :

const User = require("../models/users.model");
const shortId = require("shortid");
const jwt = require("jsonwebtoken");
const expressJwt = require("express-jwt");


exports.signupController = (req, res) => {
  // check if user is already registered
  User.findOne({ email: req.body.email }).exec((err, user) => {
    if (user) {
      return res.status(403).json({ error: "User already exists" });
    }
    const { name, email, password, confirmPassword } = req.body;
    let username = shortId.generate();
    let profile = `${process.env.CLIENT_URL}/profile/${username}`;
    let newUser = new User({ name, email, password, profile, username });
    newUser.save((err, success) => {
      if (err) {
        return res
          .status(500)
          .json({ error: "We could not signup you, sorry!" });
      }
      res
        .status(200)
        .json({ message: "Signup Successful. You can now sign in." });
    });
  });
};

In the Backend server.js, I have already used cors as :

const cors = require("cors");
app.use(cors());

Everything was working fine 2 days ago..but now posing error. Is there any problem with my backend or my frontend. Please help.

Upvotes: 1

Views: 293

Answers (1)

Oussama Bouthouri
Oussama Bouthouri

Reputation: 655

You can access your front end from the URL http://localhost:3000 instead of http://127.0.0.1:3000 this will fix the issue.

Note: CORS can only be fixed from the backend when you enable it for a certain domain

Upvotes: 2

Related Questions