Home > OS >  Post request has been blocked due to CORS error
Post request has been blocked due to CORS error

Time:08-10

My server.js file(backend) I am trying to send a POST request to an API with multipart data.

I test the API in postman and everything works fine in Postman. But when I call the API in react, it gives me CORS error.

I cross-checked the URL, Header, and Data, all seems OK for me. I go through multiple Stack Overflow question on the same topic and found that I need to pass allow-cross-origin along with the header. I added that in my header but didn't able to solve my problem.

const express = require("express");
const cors = require("cors");
// import the route
const authRoute=require("./routes/auth")
const { connection } = require("./config/db");
const postRout=require("./routes/posts")


const app = express();

var bodyParser = require('body-parser')
app.use('/api/user', authRoute)
app.use('/api/posts',postRout)


app.use(cors());
app.use(bodyParser.json())

var jsonParser = bodyParser.json()
const PORT =  8080;

app.listen(process.env.PORT || PORT, async () => {
    await connection.authenticate();
    connection.sync({ alter: true });
    // .then((data)=>{

        console.log("listening on PORT: "   PORT);
    //  console.log(data)
    // })
    console.log("hello world")
});
process.on("unhandledRejection",err=>{
    console.log(`ERROR: ${err.message}`);
    

})

my react.js file(frontEnd)

import React from "react";
import Grid from "@mui/material/Grid";
import { Container } from "@mui/system";
import sideImage from "../../Img/pexels-maria-orlova-4940756 1.png";
import Logo from "../../Img/xshopper-logo 1 (1).png";
import { Checkbox } from "@mui/material";
import Icon from "../../Img/image 1.png";
import { useState } from "react";
import axios from "axios";
import "./style.css";

const Index = () => {
  const [Email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const handleSubmit = async (e) => {
    e.preventDefault();
    console.log(password, Email);

    try {
      const res = await axios.post(
        `http://localhost:8080/api/user/login/`,
       
        {
          email: Email,
          password: password,
        }
      );

      console.log("CBM", { res });
      // console.log(items);
    } catch (error) {
      if (error.request) {
        console.log(error.response);
        console.log("server responded");
      } else if (error.request) {
        console.log("network error");
      } else {
        console.log("CBM", { error });
      }
    }
  };

  return (
    <div className="body">
      <form onSubmit={handleSubmit}>
        <Container maxWidth>
          <Grid container>
            <Grid xs={6} lg={4} md={4}>
              <img
                className="side-image"
                src={sideImage}
                alt=""
                width={"auto"}
                height={"500"}
              />
              <div className="color"></div>
            </Grid>
            <Grid justifyContent={"center"} xs={12} lg={8} md={8}>
              <img src={Logo} className="Logo" alt="image logo" width={200} />
              <br></br>
              <button className="gmail-button">
                <img src={Icon} alt="" width={25} /> Sing in with Google
              </button>
              <br></br>

              <h1>Or sing in with email</h1>

              <p className="Email-password">Email*</p>
              <input
                type="text"
                value={Email}
                onChange={(e) => setEmail(e.target.value)}
                className="input"
                name=""
                id=""
              />
              <p className="Email-password2">Password*</p>
              <input
                type="text"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                className="input"
                name=""
                id=""
              />
              <div className="forget-section">
                <div>
                  <Checkbox {..."Remember me"} />
                  <label className="remember-me" htmlFor="Remeber me">
                    {" "}
                    Remember me{" "}
                  </label>
                </div>
                <div>
                  <label className="forget-passwrod" htmlFor="">
                    Forget Passwword
                  </label>
                </div>
              </div>
              <button className="forget-button">Login</button>
            </Grid>
          </Grid>
        </Container>
      </form>
    </div>
  );
};

export default Index;

when i send post requet usning axios.post method i get this outupt

LoginRoute.js

const express =require("express")
var bodyParser = require('body-parser')
const router = express.Router();
var jsonParser = bodyParser.json()
const ProductService=require("../service/productService")
const bcrypt =require("bcryptjs")
const jwt =require("jsonwebtoken")
// validation
const {registerValidation ,loginValidation}=require("../validation")
router.post("/register",jsonParser, async (req, res)=>{
    
    const { error } = registerValidation(req.body);

    // validate:
    if(error) return res.status(400).send(error.details[0].message);

    // check the user if the email is already exist:
    const emailExist= await ProductService.getById(req.body.email)
    if(emailExist) return res.status(400).send("Email already exist")

    // hashing the password:
    const salt=await bcrypt.genSalt(10);
    const hashPassword=await bcrypt.hash(req.body.password,salt)
   
    console.log(req.body.name," ", req.body.email," ", req.body.password)
    const product = ProductService.create({
        name:req.body.name,
        email:req.body.email,
        password:hashPassword,
    });

    res.status(200).json({
        success: true,
        data: product,
    });


})

router.get("/", (req, res) => {
    res.setHeader("Access-Control-Allow-Origin", "*")
    res.setHeader("Access-Control-Allow-Credentials", "true");
    res.setHeader("Access-Control-Max-Age", "1800");
    res.setHeader("Access-Control-Allow-Headers", "content-type");
    res.setHeader( "Access-Control-Allow-Methods", "PUT, POST, GET, DELETE, PATCH, OPTIONS" ); 
     });

// Login page
router.post("/login",jsonParser, async(req,res)=>{
    
    const { error } = loginValidation(req.body);

    // validate:
    if(error) return res.status(400).send(error.details[0].message);

    // check the user if the email is already exist:
    const emailExist= await ProductService.getById(req.body.email)
    if(!emailExist) return res.status(400).send("Email Not found or password is incorect")
    // Password checeking:
    const validPass= await bcrypt.compare(req.body.password,emailExist.password);
    if(!validPass) return res.status(400).send("Invalid Password");
    
    const token=jwt.sign({id:emailExist.id},"dfhdfhdhfkjh");
    res.header("Auth-token",token).send("success")
})

module.exports =router

CodePudding user response:

if your frontend run on port 3000 it should look like include this on your server.js

var corsOptions = {
    origin: 'http://localhost:3000',
    optionsSuccessStatus: 200 // For legacy browser support
}

app.use(cors(corsOptions));

CodePudding user response:

Try using chrome extension to unblock Cors like this:

https://chrome.google.com/webstore/detail/cors-unblock/lfhmikememgdcahcdlaciloancbhjino?hl=pt-BR

  • Related