Home > Software engineering >  No 'Access-Control-Allow-Origin' in express app
No 'Access-Control-Allow-Origin' in express app

Time:09-25

No 'Access-Control-Allow-Origin' in express app Getting error in this code

  function login(username, password) {
        const requestOptions = {
            method: 'POST',
            headers: {    
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                'Access-Control-Allow-Origin': '*' },
            body: JSON.stringify({ username, password })};
    
    return fetch(`http://localhost:5000/admin/authenticate`, requestOptions)
            .then(handleResponse)
            .then(user => {
                // store user details and jwt token in local storage to keep user logged in between page refreshes
                localStorage.setItem('user', JSON.stringify(user));
                return user;
            }
        );
    }

CodePudding user response:

FOR NODE EXPRESS Add this header middleware to avoid CORS and any POST or OPTIONS error in your root file app.js or server.js

app.use((req, res, next) => {
      res.setHeader("Access-Control-Allow-Origin", "*");
      res.setHeader(
        "Access-Control-Allow-Methods",
        "OPTIONS, GET, POST, PUT, PATCH, DELETE"
      );
      res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
      if (req.method === "OPTIONS") {
        return res.sendStatus(200);
      }
      next();
    });
  • Related