user9705886
user9705886

Reputation:

Unauthorized in getting request : MEAN Stack

For validation in my code, I'm using the passport.js. When I'm using get request method I'm getting error as

Failed to load http://localhost:3000/users/profile: Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.

This is my code.

    authToken: any;
        getProfile() {
            let headers = new Headers();
            this.loadToken();
            headers.append('Authorization', this.authToken);
            headers.append('Content-Type','application/json');
            return this.http.get('http://localhost:3000/users/profile',{headers: headers})
              .map(res => res.json());
          }
        loadToken(){
           const token = localStorage.getItem('id_token');
           this.authToken = token;
         }
storeUserData(token, user){
    localStorage.setItem('id_token', token);
    localStorage.setItem('user', JSON.stringify(user));
    this.authToken = token;
    this.user = user;
  }

This is from my routes file

// Profile
router.get('/profile', passport.authenticate('jwt', {session:false}), (req, res, next) => {
    res.json({user: req.user});
  });

Upvotes: 0

Views: 883

Answers (1)

Alexis Facques
Alexis Facques

Reputation: 1873

You're having trouble with Cross-Origin Resource Sharing (CORS): a mechanism that gives webservers cross-domain access controls, which enable secure cross-domain data transfers.

Easiest fix, npm i cors and then in your Express.js app, before anything else:

const cors = require('cors');
var app = express();
app.use(cors());

Or if you don't want an additional dependency:

var app = express();
app.use( (req,res,next) => {
   res.header('Access-Control-Allow-Origin', '*');
   res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
   next();
})

Upvotes: 1

Related Questions