1

Currently developing the elasticsearch API application, I need to get the header request from AJAX call in server side. Ajax request given below.

$.ajax({
          url: 'http://localhost:3002/api/v1/getAutoSuggest/'+elasticsearchIndex+'/'+elasticsearchType,
          dataType: 'JSONP',
          type: 'GET',
          beforeSend: function(xhr){xhr.setRequestHeader('access-control-request-headers', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9');},
          success: function (data) {

          }
});

In nodejs, I tried to get by using req.headers['x-access-token'] but couldn't get it.

var checkToken = app.use(function(req, res, next) {
var token = req.param.token || req.headers['x-access-token'];

  if (token) {
    jwt.verify(token, config.secret, function(err, decoded) {      
      if (err) {
        return res.json({ success: false, message: 'Failed to authenticate token.' });    
      } else {

   req.decoded = decoded;    
        next();
      }
    });

  } else {
  }
});

And also I have added the following statements in nodejs server side.

 var allowedOrigins = ['http://127.0.0.1:8000', 'http://localhost:8000', 'http://127.0.0.1:9000', 'http://localhost:9000'];
     var origin = req.headers.origin;
     if(allowedOrigins.indexOf(origin) > -1){
       res.setHeader('Access-Control-Allow-Origin', origin);
     }

    res.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
res.header('Access-Control-Allow-Headers', 'access-control-request-headers');
    res.header('Access-Control-Expose-Headers', '*');
    res.header('Access-Control-Allow-Credentials', true);

But getting token in lowercase eyjhbgcioijiuzi1niisinr5cci6ikpxvcj9 .

Thanks in advance!

2
  • req.headers['x-access-token'] works for me Commented Dec 23, 2016 at 11:48
  • what console.log(JSON.stringify(req.headers)) return? Commented Dec 23, 2016 at 11:49

1 Answer 1

1

You cannot set headers when using JSONP. The reason for that is because when using JSONP for cross domain requests, jquery implements this by injecting a special <script> tag into the DOM in order to load the remote resource. And as you know, when using <script> tags you have no way of specifying custom headers.

An alternative approach to JSONP would be to use CORS. The server will need to support it and explicitly allow the origins and headers that need to be set.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.