Ad

Unable To Fix CORS In Post Request

- 1 answer

I'm creating a MERN stack project, where I need to make a signup and login requests.

I'm unable to make a POST request from a client-side, it's throwing error.

`

Access to XMLHttpRequest at 'http://localhost:5000/users/signup' from origin 'http://localhost:3000' 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.
Signup.js:49 Error: Network Error
    at createError (createError.js:16)
    at XMLHttpRequest.handleError (xhr.js:83)
xhr.js:178 POST http://localhost:5000/users/signup net::ERR_FAILED

`

The codes are-

cors.js


    const cors = require("cors");

    const whitelist = [
      "http://localhost:3000",
      "https://localhost:3443",
      "http://localhost:3001"
    ];
    var corsOptionsDelegate = (req, callback) => {
      var corsOptions;
      console.log(req.header("Origin"));
      if (whitelist.indexOf(req.header("Origin")) !== -1) {
        corsOptions = { origin: true };
      } else {
        corsOptions = { origin: false };
      }
      callback(null, corsOptions);
    };

    exports.cors = cors();
    exports.corsWithOptions = cors(corsOptionsDelegate);

node user.router.js

...

    const cors = require("../auth/cors.js");

    const userRouter = express.Router(); // initialize express router

    userRouter
      .post("/signup", cors.corsWithOptions, (req, res, next) => {
        console.log(req.body);
        User.register(
          new User({
            username: req.body.username,
            email: req.body.email,
            firstName: req.body.firstName,
            lastName: req.body.lastName
          }),
          req.body.password,
          (err, user) => {
            if (err) {
              res.statusCode = 500;
              res.setHeader("Content-Type", "application/json");
              res.json({ err: err });
            } else {
              if (req.body.firstName) user.firstName = req.body.firstName;
              if (req.body.lastName) user.lastName = req.body.lastName;
              user.save((err, user) => {
                if (err) {
                  res.statusCode = 500;
                  res.setHeader("Content-Type", "application/json");
                  res.json({ err: err });
                  return;
                }
                passport.authenticate("local")(req, res, () => {
                  res.statusCode = 200;
                  res.setHeader("Content-Type", "application/json");
                  res.json({ success: true, status: "Registration Successful!" });
                });
              });
            }
          }
        );
      })

    ...

react signup.component.js


    signup = e => {
    if (!isEmpty) {
          const newUser = this.state.userDetail;
          console.log(newUser);
          this.setState({ loadingIsTrue: true });
          // axios
          //   .get(process.env.REACT_APP_API_BASE_URL + "users/list")
          //   .then(res => console.log(res))
          //   .catch(err => console.log(err));
          axios
            .post(process.env.REACT_APP_API_BASE_URL + "users/signup", {
              ...newUser
            })
            .then(res => console.log(res))
            .catch(err => console.log(err));
        } else alert("Please fill all the details first to signup");
      };

Note: when request is made from POSTMAN, it is successful, and the database is updated correctly

Ad

Answer

See the documentation:

Certain CORS requests are considered ‘complex’ and require an initial OPTIONS request (called the “pre-flight request”). An example of a ‘complex’ CORS request is one that uses an HTTP verb other than GET/HEAD/POST (such as DELETE) or that uses custom headers. To enable pre-flighting, you must add a new OPTIONS handler for the route you want to support

You've only bound the CORS middleware to userRouter.post.

Ad
source: stackoverflow.com
Ad