How to access HTTP headers of request in AngularJS - javascript

I know I can access an HTTP request's GET parameters in AngularJS with
$location.search().parameterOfInterest
But how do I access HTTP headers of the request?
I'm not using $http here. I'm asking about request to an AngularJS web page.
This question and answers makes me believe this is could be not possible:
Accessing the web page's HTTP Headers in JavaScript

You can use a request interceptor that is called with an HTTP configuration object. An HTTP configuration object has a header property that you can freely access / modify inside your interceptor.
The response object of promise also has a header property that you can access.

Related

Request objects and response object

In express.js, middlewares can change request object and response object. So, my question is what exactly these request object and response object are and what do they contain.
From expressjs documentation a request is:
The req object represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on.
And the response:
he res object represents the HTTP response that an Express app sends when it gets an HTTP request.
Basically you use a request to know what the client is asking for.
And you use the response object to send the response data to the client.
Had the same questions when i started with express. I found a nice article, explaining my questions.
http://www.murvinlai.com/req-and-res-in-nodejs.html
UPDATE
from the page:
What is Req & Res?
Req -> Http (https) Request Object.
You can get the request query, params, body, headers and cookies from it.
You can overwrite any value or add anything there.
However, overwriting headers or cookies will not affect the output back to the browser.
Res -> Http (https) Response Object.
The response back to the client browser.
You can put new cookies value and that will write to the client browser (under cross domain rules)
Once you res.send() or res.redirect() or res.render(), you cann do it again, otherwise, there will be uncaught error.
Me too had this same doubts.
Request Object
The req object represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on
Response Object
The res object represents the HTTP response that an Express app sends when it gets an HTTP request.
Reference Link

"Access-Control-Allow-Origin" Request Error When Accessing API [duplicate]

This question already has answers here:
XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header
(11 answers)
Closed 3 years ago.
I'm unable to retrieve data from the Rescue Time API. I'm making a request in a JavaScript file using the jQuery get() method. Here is a look at the JavaScript related to the API GET request:
$.get('https://www.rescuetime.com/anapi/data?key=########################&format=json&restrict_kind=overview', function(data) {
// callback function code...
});
The "key=########################" is the paramater that includes my API key.
When running the script (either locally or on my personal domain), I receive a cross origin error:
XMLHttpRequest cannot load https://www.rescuetime.com/anapi/data?key=########################&format=json&restrict_kind=overview. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
I understand that this is happening because i'm requesting content that is on a different domain than the one that is making the AJAX request. That being said, how do I get around this? I've read the CORS MDN documentation, but could not decode what actionable steps I need to follow in order to resolve this issue.
I need some actionable steps.
Set up a CORS proxy using the code from https://github.com/Rob--W/cors-anywhere/ or similar.
https://cors-anywhere.herokuapp.com/ is a public instance running that code, and the way you could use it is by changing your existing code to this:
$.get('https://cors-anywhere.herokuapp.com/https://www.rescuetime.com/anapi/data?key=########################&format=json&restrict_kind=overview', function(data) {
// callback function code...
});
Be aware though that if you do that, your key would potentially be exposed to the operator of that https://cors-anywhere.herokuapp.com/ instance. So if that’s a concern then don’t try it, and instead set up your own proxy at https://some.url.for.your.proxy and change your code to:
$.get('https://some.url.for.your.proxy/https://www.rescuetime.com/anapi/data?key=########################&format=json&restrict_kind=overview', function(data) {
// callback function code...
});
Either way the result will be that your request gets sent through the specified CORS proxy, which forwards the request to the https://www.rescuetime.com/anapi/data… endpoint and then receives the response. The proxy backend then adds the Access-Control-Allow-Origin header to the response and finally passes that back to your requesting frontend code.
Your browser then allows your frontend code to access the response, because that response with the Access-Control-Allow-Origin response header is what the browser sees. Otherwise, if the response lacks Access-Control-Allow-Origin, browsers won’t let your code access it.
A CORS proxy like that is the only option if you want to make the request from frontend JavaScript code running in a browser, and want to consume the response from that frontend code. Otherwise, without the use of such a proxy, browsers will block your code from accessing the response—because the https://www.rescuetime.com/anapi/data… API endpoint doesn’t itself send the necessary Access-Control-Allow-Origin response header.
Your only other option otherwise is to not make the request from your frontend code but instead make the request from whatever backend server-side code you’re running. In that case there’s no browser in the middle enforcing cross-origin restrictions on the request.

Sending POST, GET and COOKIE data with AJAX request

The POST and GET data are done very easily with ajax. I can't find a way to 'include' a cookie. How can I include a 'cookie'?
There is no way to explicitly add a cookie to an XMLHttpRequest request (or for any of the other techniques used for Ajax). The setRequestHeader method explicitly forbids setting cookies.
You need to add a cookie through the normal methods (i.e. via the HTTP Set-Cookie response header and the JS document.cookie API) and then make the request.
You'll also need to set xml.withCredentials = true; for a cross-origin request (and the cookie will need to belong to the host you are making the request to, not the document hosting the JS making the request).

Execute route if only the local Angular App calls it true the controller

I have a few API routes that only the app itself (controller.js) should have access to. Is there a way to use an IP address (possibly insecure because of spoofing) to create a restriction of who uses this part of the api?
Server size (server.js)
app.get("/api/specs",function(req,res){
// Only the app should have access to it, not external entities
res.json({used:getUsed()});
});
Client side (controller.js)
$http.get('/api/specs').success(function(specs,code){
console.log(specs);
});
By default your browser doesn't allow you to make Cross-site HTTP requests because are subject of the same origin policy.
Note:
In particular, this meant that a web application using XMLHttpRequest
could only make HTTP requests to the domain it was loaded from, and
not to other domains.
Which it means in your case that only the js in the same domain of your api can have access to them.
What if I want to extend the use of the API to other domains?
Well in this case you have to setup in your backend api the Access-Control-Allow-Origin header.
Some eg:
// Cross-site HTTP requests from http://siteA.com
Access-Control-Allow-Origin: http://siteA.com
// Cross-site HTTP requests from all
Access-Control-Allow-Origin: *
If you want to debug this behaviour you can just open firebug and check in networks the headers of your requests.
References:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy
I suppose that using a GET parameter is the easiest way.
Node.js(express)
app.get("/api/specs",function(req,res){
var queryParam = url.parse(req.url,true).query
if(queryParam.whois == "yourUniqueName"){
res.send("okay");
}else{
res.status(404);
res.send("NG");
}
});
angular
$http.get("/api/specs", {
params: { whois: "yourUniqueName" }
});
define names something unique for each APIs.
and set the server returns response only when a client sends correct name.
server returns 404 except you pass yourUniqueName as query parameter whois.
/api/specs?whois=yourUniqueName
okay
.
/api/specs?whois=otherName
/api/specs?otherParam=something
/api/specs
NG

How to make a JSONP POST request in angular?

The $http.jsonp method described in the official documentation seems to always perform get requests: http://docs.angularjs.org/api/ng.$http#methods_jsonp.
I have tried setting the config option to 'POST' but it still sends a GET:
$http.jsonp('/api/new?callback=JSON_CALLBACK', {method: 'POST'});
I have also tried setting a data argument in the hope that angular would switch to a POST:
$http.jsonp('/api/new?callback=JSON_CALLBACK', {data: {stuff: true}});
But it still doesn't :)
As for making a post like this:
$http.post('/api/new?callback=JSON_CALLBACK')
It does make a POST obviously but doesn't do the angular magic thingy with the JSON_CALLBACK and produces the following JS error:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://xxx.yyy.zzz' is therefore not allowed access.
(The API is not on the same server as the app, that's the point of JSONP).
Google was most unhelpful on this issue and reading through angular's sources is not the easiest task. So how can I make a JSONP POST request with angular?
You cannot make a POST request using JSON-P (with or without Angular)
A JSON-P request works by generating a <script> element with a src attribute. This will always trigger a GET request.
If you want to make a cross-domain POST request with JavaScript then you must use either XMLHttpRequest (and have the server supply suitable access control headers as per the CORS specification) or proxy the request through the server hosting the page.

Categories

Resources