0

I am trying to make a request from my client side React JS to server side Node JS and Backend on MongoDB. But whenever I am trying to make a post request for my login functionality but it is giving me the below error and I am using VITE for my react project and my route is : http://127.0.0.1:5173/login

login:1 Access to XMLHttpRequest at 'http://localhost:8800/api/auth/login' from origin 'http://127.0.0.1:5173' 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.
{
    "message": "Network Error",
    "name": "AxiosError",
    "stack": "AxiosError: Network Error\n    at XMLHttpRequest.handleError (http://127.0.0.1:5173/node_modules/.vite/deps/axios.js?v=b0cda0cd:1440:14)",
    "config": {
        "transitional": {
            "silentJSONParsing": true,
            "forcedJSONParsing": true,
            "clarifyTimeoutError": false
        },
        "adapter": [
            "xhr",
            "http"
        ],
        "transformRequest": [
            null
        ],
        "transformResponse": [
            null
        ],
        "timeout": 0,
        "xsrfCookieName": "XSRF-TOKEN",
        "xsrfHeaderName": "X-XSRF-TOKEN",
        "maxContentLength": -1,
        "maxBodyLength": -1,
        "env": {},
        "headers": {
            "Accept": "application/json, text/plain, */*",
            "Content-Type": "application/json"
        },
        "withCredentials": true,
        "method": "post",
        "url": "http://localhost:8800/api/auth/login",
        "data": "{\"username\":\"as\",\"password\":\"as\"}"
    },
    "code": "ERR_NETWORK",
    "status": null
}
POST http://localhost:8800/api/auth/login net::ERR_FAILED

Below is my client side code:

const Login = () => {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState(false);

  const handleSubmit = async (e) => {
    e.preventDefault();

    try {
      const res = await axios.post(
        "http://localhost:8800/api/auth/login",
        {
          username,
          password,
        },
        {
          withCredentials: true,  
        }
      );
      console.log(res);
    } catch (err) {
      setError(err);
      console.log(error);
      console.log(err);
    }
  };

  return (
    <div className="login">
      <form onSubmit={handleSubmit}>
        <h1>Sign in</h1>
        <label htmlFor="">Username</label>
        <input
          type="text"
          name="username"
          placeholder="ahmed"
          onChange={(e) => setUsername(e.target.value)}
        />

        <label htmlFor="">Password</label>
        <input
          type="password"
          name="password"
          placeholder="password"
          onChange={(e) => setPassword(e.target.value)}
        />

        <button type="submit">Login</button>
      </form>
    </div>
  );
};

This is my server.js file:

const express = require("express");
const mongoose = require("mongoose");
const cookieParser = require("cookie-parser");
const dotenv = require("dotenv");
const userRoute = require("./routes/user.route.js");
const gigRoute = require("./routes/gig.route.js");
const orderRoute = require("./routes/order.route.js");
const messageRoute = require("./routes/message.route.js");
const conversationRoute = require("./routes/conversation.route.js");
const reviewRoute = require("./routes/review.route.js");
const authRoute = require("./routes/auth.route");
const cors = require("cors");

const app = express();

app.use(express.json());
app.use(cookieParser());
dotenv.config();
mongoose.set("strictQuery", true);

function handleError(error) {
  console.error("An error occurred:", error);
}

async function startServer() {
  try {
    await mongoose.connect(process.env.MONGO);
    console.log("conneted!");
  } catch (error) {
    handleError(error);
  }
}

app.use("/api/users", userRoute);
app.use("/api/auth", authRoute);
// app.use("/api/gigs", gigRoute);
// app.use("/api/orders", orderRoute);
// app.use("/api/conversations", conversationRoute);
// app.use("/api/messages", messageRoute);
// app.use("/api/reviews", reviewRoute);

// error handling middleware
app.use((err, req, res, next) => {
  const errorStatus = err.status || 500;
  const errorMessage = err.message || "Something went wrong!";

  return res.status(errorStatus).send(errorMessage);
});

//
app.use( //here i am using cors
  cors({
    origin: "*",
  })
);

app.listen(8800, () => {
  startServer();
  console.log("app is listening at 8800!");
});

auth.route.js file:

const express = require("express");
const { register, login, logout } = require("../controllers/auth.controller");

const router = express.Router();

router.post("/register", register);
router.post("/login", login);
router.post("/logout", logout);

module.exports = router;

and in the end it is my auth.controller.js file:

const User = require("../models/user.model");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const { createError } = require("../utils/createError");
const login = async (req, res, next) => {
  try {
    const user = await User.findOne({ username: req.body.username });
    if (!user) return next(createError(404, "user not found!"));

    const isCorrect = bcrypt.compareSync(req.body.password, user.password);
    if (!isCorrect)
      return next(createError(400, "Wrong password or username!"));

    const token = jwt.sign(
      {
        id: user._id, //object id
        isSeller: user.isSeller,
      },
      process.env.JWT_KEY
    );

    const { password, ...info } = user._doc;
    res.header("Access-Control-Allow-Origin", "http://127.0.0.1:5173");
    res
      .cookie("accessToken", token, {
        httpOnly: true,
      })
      .status(200)
      .send(info);

    res.status(200).send(user);
  } catch (err) {
    next(err);
  }
};
const logout = async (req, res) => {
  res
    .clearCookie("accessToken", {
      sameSite: "none",
      secure: true,
    })
    .status(200)
    .send("User has been logged out!");
};
const register = async (req, res, next) => {
  try {
    const hash = bcrypt.hashSync(req.body.password, 5);
    const newUser = new User({ ...req.body, password: hash });
    await newUser.save();
    res.status(201).send("User has been created");
  } catch (err) {
    next(err);
  }
};
module.exports = {
  login,
  logout,
  register,
};

Steven
  • 231
  • 1
  • 8
  • localhost and 127.0.0.1 are not necessary the same thing. (localhost is commonly also ::1.) Does it work if you used the same domain in both places? – ikegami Apr 08 '23 at 16:41
  • same domain where? – Steven Apr 08 '23 at 16:44
  • The error says you requested a page from localhost from a page from 127.0.0.1 – ikegami Apr 08 '23 at 16:57
  • yes it saying ```from origin 'http://127.0.0.1:5173'```. Sorry I am beginner in MERN and not getting what are you saying. Can you explain more what changes should I make? – Steven Apr 08 '23 at 17:08
  • But the page isn't ocming from 127.0.0.1, it's coming from localhost. Change it to localhost. Not saying it's going to work, but it's worth a try. Either use 127.0.0.1 everywhere, or use localhost everywhere. – ikegami Apr 08 '23 at 17:08
  • This Didn't work. – Steven Apr 08 '23 at 17:18
  • Why is your client running on a completely different domain and port? – Mike 'Pomax' Kamermans Apr 08 '23 at 17:21
  • Why is your client running on a completely different domain and port? And why are you using Vite if you've written your own server.js? Vite already handles that, you should not have one...? – Mike 'Pomax' Kamermans Apr 08 '23 at 17:27
  • You need to register the `cors()` middleware **before** your routes – Phil Apr 12 '23 at 04:40

1 Answers1

-1

i had the same error but i solved by this way. on your server.js try to use this code : app.use(cors({ origin: "http://127.0.0.1:5173", credentials: true })) instead of what you use above. after this go to your login page write this code const res= await axios.post("http://127.0.0.1:8800/api/auth/login",{ username, password, }) you can or not write the credentiel parameter in this line it will works.

pato
  • 1