How to access angular $http response custom headers? - ajax

Here is my code:
$http({
method: 'POST',
url: myURL,
headers: {
//BLAH
},
data: {
// BLAH BLAH
}
}).success(function(data, status, headers) {
deferred.resolve({
// This is not possible:
sessionId: headers('sessionId')
});
});
I would like to access sessionId attribute from headers, but only header I seem to find is Content-Type.
What may be the cause why this does not work?

I found this post useful: https://github.com/mgonto/restangular/issues/128
It states the following:
After research I found the solution: you have to tell your api server to "expose" the custom headers. You can do this by using the Access-Control-Expose-Headers header. The value is the headers you want to be able to access. So it'd look like: Access-Control-Expose-Headers: Your-Header, Another-Header.
Adding this extra header solved my problem.

Related

Remove some cookie from ajax call with Axios

I use Axios in browser to call ajax request. Now I have a problem with some cookie that has high priority than some header. Per request I send a header as AUTHTOKEN but in cookie SESSIONID key stored that high priority than AUTHTOKEN header. In some scenario, I need to ignore cookie. This is my code:
axios({
url:`${sdpBasicUrl}/api/v3/requests/27363`,
method: 'get',
headers: {
'Content-Type': 'application/json'
'AUTHTOKEN': 'GHG23847923HGJ'
}
})
.then(res => {
console.log(res.data);
});
and this is cookie sample:
_z_identity=true; PORTALID=1; csrfcookie=aasdasdjh24234b2bjh4hjl; SESSIONID=ffd68d32a14841c99905e3cf4897e15ec9b4777020854a76821fd7e1eab6db2dcab482eb4cfea2ce7f5a6c47c80271d09f608ed985004e5c85681b2939681b18
What should I do? Do you have any solution to solve my problem?
You are able to pass in cookies through the header like this:
Axios.request({
url: "http://example.com",
method: "get",
headers:{
Cookie: "cookie1=value; cookie2=value; cookie3=value;"
}
}).then...
So if you don't want the value to be there, you could override the values.
https://github.com/axios/axios/issues/943
You can use transformRequest to modify the header for some requests. transformRequest allows changes to the request data and header before it is sent to the server. This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE'.
transformRequest: [function (data, headers) {
// Modify the header here and return the header
return data;
}],
You can get more information about it on https://axios-http.com/docs/req_config

Getting response headers from Ajax POST in ExtJS

Given this Ext.Ajax call:
Ext.Ajax.request({
url: url,
method: 'POST',
jsonData: dataToPost,
success: function (response) {
console.log(response.getAllResponseHeaders());
console.log(response.getResponseHeader('Location'));
console.log(response.getResponseHeader('location'));
});
}
I expected to see the Location: header in the log. Instead I get this (I added the lower-case location just in case, seeing content-type is lower-case):
The same request seen in Fiddler shows more headers than Content-type:
What am I doing wrong?

javascript: how to make AJAX call based on the avaiable cURL request

Currently in my web app project, I need to parse the content of a web page, and after some searching, I found that Mercury Web Parser API is quite suitable for me.
And I have some experience with such kind of third party APIs, generally speaking I can get my desired result.
But for this API, I can't find documentation about the API usage on the official website.
Based on the my study, it provide two methods:
first is cURL as following:
curl -H "x-api-key: myapikey" "https://mercury.postlight.com/parser?url=https://trackchanges.postlight.com/building-awesome-cms-f034344d8ed"
the myapikey is the API key I get from the website. Then I can get the result in JSON format, which is the main content of the web page specified by the url parameter. It works well for me, I mean the cURL method.
And on the website, it said that the second method is HTTP call, which is just what I need:
GET https://mercury.postlight.com/parser?url=https://trackchanges.postlight.com/building-awesome-cms-f034344d8ed
Content-Type: application/json
x-api-key: myapikey
So based on my understanding, I use jquery AJAX method to do this as following:
var newurl = "https://mercury.postlight.com/parser?url=http://www.businessinsider.com/joel-spolsky-stack-exchange-interview-2016-12&x-api-key=myapikey"
$.ajax({
url: newurl,
dataType: "jsonp",
success: function(data){
console.log(data.title);
}
})
here I made JSONP request because of the Cross origin issue.
But now I face 401 error message (401 Unauthorized. The request has not been applied because it lacks valid authentication credentials for the target resource)
For now my guess is that the apikey is not correctly passed to server. So based on the cURL's successful call, can I get the correct format for AJAX call?
Update:
Based on the following answers ,I tried to set the request header as following:
$.ajax({
url: newurl,
dataType: "jsonp",
beforeSend: function(xhr){
console.log(apiKey);
xhr.setRequestHeader('x-api-key', apiKey);
},
/*
headers: {
"x-api-key": "M1USTPmJMiRjtbjFNkNap9Z8M5XBb1aEQVXoxS5I",
"contentType": 'application/json'
},
*/
success: function(data){
console.log("debugging")
console.log(data.title);
},
error: function (error) {
console.log(error)
}
})
I tried both beforeSend and headers. But still can't work and get the following trackback error message:
send # jquery.js:8698
ajax # jquery.js:8166
addNewArticle # topcontroller.js:18
fn # VM783:4
e # angular.js:281
$eval # angular.js:147
$apply # angular.js:147
(anonymous) # angular.js:281
dispatch # jquery.js:4435
elemData.handle # jquery.js:4121
And for the last send function, still 401 error.
But the ajax error handling part shows that the readyState:4 and status: 404 result. So what's going here.
For your question, the curl request is sending a header which you have attached as part of the query string in your $.ajax request.
Try the following instead (using beforeSend + xhr) :
// broke this string down so you don't have to scroll
var newurl = "https://mercury.postlight.com/parser?" +
"url=http://www.businessinsider.com/" +
"joel-spolsky-stack-exchange-interview-2016-12";
// set your api key
var apiKey = "<your api key>";
$.ajax({
url: newurl,
dataType: "json",
beforeSend: function(xhr){xhr.setRequestHeader('x-api-key', apiKey);},
success: function(data){
console.log(data.title);
}
})

Can't retrieve my x-api-key from my request header with CORS enabled. Why?

I'm working with CodeIgniter2 Rest API and AJAX to make requests from a smartphone with PhoneGap to a AWS server with apache.
Everything was working fine when working on my localhost/browser.
But when trying to set up a distant server things got bad.
I have configured my server properly with CORS so that it allows external requests as explained here :
http://dev.nuclearrooster.com/2011/01/03/cors-with-apache-mod_headers-and-htaccess/
To secure the API, I have been setting up an API KEY that I have to pass in the header of my request like so:
$.ajax({
type:"GET",
url: server_url + 'user/available',
headers: { 'X-API-KEY': key },
dataType: 'json'
});
But then, after seeing my ajax called being refused because of an invalid API Key, I have been trying to make sure the server received the key. and it doesnt. when I try to echo my key, its empty.
I can see in my debug console the following:
Request header field X-API-KEY is not allowed by Access-Control-Allow-Headers.
So I have been modifying my .htaccess following this post:
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type, x-api-key"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
so now, the message is gone but the problem still remains the same ... why ?
How can I transmit this X-API-KEY through my AJAX call Header so I can authentificate my users ?
Many Thanks
I faced this problem and with weeks of tweaking I was able to get it to work with a hack of a job... I can't remember the exact part that did fix it but will provide with what I am currently using.
Server Side
function __construct(){
parent::__construct();
header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
header("Access-Control-Allow-Headers: X-API-KEY");
}
function available_options(){
$this->response(array('response' => array()), 200);
}
Client Side
function sendData(dataToSend, successCallback) {
window.default_headers['X-API-KEY'] = '_KEY_';
return $.ajax({
type: "POST",
url: server_url + 'user/available',
data: { data : JSON.stringify(dataToSend) }, // serializes the form's elements.
dataType: 'json',
headers: window.default_headers,
xhrFields: {
withCredentials: true
}
});
}
Since you're using a GET request, possibly using JSONP would be of more use, this avoids cross domain requests.
JSONP Request
$.ajax({
type : "GET",
dataType : "jsonp",
url: server_url + "user/available?callback=?", // ?callback=?
success: function(data){
// do stuff with data
}
});

Getting the Content-Type with AngularJS or jQuery

I want to make a directive with AngularJS which displays a media (an image or a video).
To achieve this goal I have to determine the kind of media, in order to do that I wanted to make an AJAX reqest to the url and get the Content-Type header, but I have not find something like that in the documentation.
Have you some hints to do that?
You can get all the headers with $http:
$http({method: 'GET', url: '/someUrl'}).
success(function(data, status, headers, config) {
var contentType = headers('Content-Type');
// use the content-type here
})
You can do this with jQuery:
$.ajax({
url:'/someUrl',
type: 'GET',
success:function(res, status, xhr){
var contentType = xhr.getResponseHeader('Content-Type');
}
});
After more than two hours of searching, this is the best answer I found for angularJS 1.x:
$http({
method: method,
url: url,
data: data,
header: {'Content-Type': 'application/x-www-form-urlencoded'},
timeout: 30000
})
.then(
//success function
function(response){
console.log(response.headers('content-type'));
},
//error function
function(response){
}
);
The main part is response.headers('content-type')
Note 1: This solution is applied to angular 1.x.
Note 2: This method is using then(success function,error function), which is much more better and reliable than the elder method (separate success and error)

Resources