Maksim Novikov
Maksim Novikov

Reputation: 834

Get custom header from ajax response

enter image description hereenter image description herei use nodejs with express as rest api, on client side i use jQuery (ajax) for http request. When user perform login request the server return user object as body and x-auth token in header. The problem is for some reason i don't see the x-auth header in response data. Server side code:

//POST api/login
app.post('/api/login', (req, res) => {

  var body = _.pick(req.body, ['email', 'password'])
  console.log(body)
  var user;
  User.findByCredentials(body.email, body.password).then((result) => {
    user = result
    return user.generateAuthToken()
  }).then((token) => {
    // as you see i put the token here as header, and it is not null i 
    // made debugging.
    res.status(200).header('x-auth', token).send(user) 
  }).catch((e) => {
    res.status(400).send('Unauthorized')
  })

})

Client side code:

let loginRequest = {
        "email":username,
        "password":password
      }
      loginRequest = JSON.stringify(loginRequest)
      console.log(loginRequest)
      var res = $.ajax({
        url:"http://192.168.1.22:3000/api/login",
        method: "POST",
        data: loginRequest,
        contentType: "application/json;charset=utf-8",
        dataType: 'json',
        cache: false,
        success: function(user, status, response){
          console.log('Login success :'+status);
          console.log(user.fullName +", role: "+user.role)
         //i try to print all the headers here but it not contain the x-auth 
          console.log(`${response.getAllResponseHeaders()}`)

        },
        error: function(e){
          console.log("login error, status: "+e.status +" message : 
                                              "+e.responseText);
        }
      })

When i print all the headers : response.getAllResponseHeaders() the result is : content-type: application/json; charset=utf-8

I also have android client for this api and in android i do have the x-auth header. Do i miss something in ajax ?

Upvotes: 1

Views: 681

Answers (2)

Nuriddin Kudratov
Nuriddin Kudratov

Reputation: 518

I think everything is fine with your code and the problem is about cross-origin-resource-sharing. Before you make a post request to url:"http://192.168.1.22:3000/api/login", your browser checks if there is access for an incoming request from outside in your API (server), if yes, then your request will be sent to the server. In order to enable an incoming request from outside, you should use cors

Upvotes: 0

Maksim Novikov
Maksim Novikov

Reputation: 834

After hundreds of tries i found that because it was CORS request, i was needed add Access-Control-Expose-Headers to res.header at server side

full code for express middleware in server :

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*")
  res.header('Access-Control-Expose-Headers', 'x-auth'); //added this line
  res.header("Access-Control-Allow-Headers", "Origin, headers, X-Requested-With, Content-Type, contentType, Accept, x-auth");
  next()
})

Upvotes: 2

Related Questions