1

I have created a basic angular $http.post request to receive some data. In order to receive the data I need to provide a key in the header.

The server is responding that the key is missing even though I've explicitly sent it.

100% it's not the server because I used an online curl tool which provided the required response.

$http.post(url, {        
    data:{username: username,password: password},
    headers:{'Content-Type': 'application/x-www-form-urlencoded','key': key},
  })
  .then(function(response){
    console.log(response)
  })

It would be appreciated if someone could spot what I'm doing wrong here. Thanks.

Andrew Turnbull
  • 33
  • 1
  • 2
  • 7
  • I would use a browser developer tool to sniff the XHR requests to ensure the header is not being sent correctly. For example, in Chrome you can use the Developer Tools to inspect XHR requests, and view everything sent from a request. – Pixxl Jul 15 '15 at 21:19
  • I did this, played with the code and now got it to accept the 'key' header. But now it's no accepting the data I have sent with it. Any ideas? – Andrew Turnbull Jul 15 '15 at 21:54
  • What type of backend server is handling the request? Maybe you need to look into how to properly handle the data or if needed, encode/decode it – Pixxl Jul 16 '15 at 19:48
  • I had a similar issue previously and solved it by adding a transformRequest to the httpProvider during the app config stage. Credit to kzar who provided the code here: https://stackoverflow.com/a/19633847/2347498 – MikeyM Jul 15 '15 at 23:01

2 Answers2

0

You have a trailing comma after the headers key, perhaps this is throwing things off?

$http.post(url, {        
  data:{username: username,password: password},
  headers:{'Content-Type': 'application/x-www-form-urlencoded','key': key}, // Remove this comma
})
.then(function(response){
  console.log(response)
});
Chrillewoodz
  • 27,055
  • 21
  • 92
  • 175
0

According to docs should be:

Shortcut method

  $http.post('http://localhost:9191/api/signin', {
    username: 'some username',
    password: 'some password'
  }, {
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'key': '123'
    }
  })
  .then(function(response) {
    console.log(response)
  });

Long version

$http({
  method: 'POST',
  url: 'http://localhost:9191/api/signin',
  data: {
    username: 'some username',
    password: 'some password'
  },
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'key': '123'
  }
}).then(function(response) {
  console.log(response)
});

Tested and is working fine.