I would like to see the http request headers in the frontend. I've been digging around in the browser's window object and saw the following:
new window.Response().headers.values()
I am aware that I can see the request headers on the backend server and then just send it as a response to the frontend, but I don't want to make the extra call instead I want to use the window object or something similar. Is such anything possible?
You can get response headers like this. The Headers class instance that fetch returns is an iterable.
fetch('https://api.sampleapis.com/wines/reds').then(function(response) {
response.headers.forEach(console.log);
});
Related
I am trying to make a POST request to an AWS Lambda Python Script I have set up.
I have already heard about solving the issue of Access-Control-Allow-Origin by adding a header to the Response from AWS lambda, that looks like Access-Control-Allow-Origin:*, and I implemented this in the code I was working on for the get request. Then when I begun creating a POST request, I did the same thing, so that the new POST request originally looked like this:
def post(event, context):
try:
return dict(
statusCode=200,
headers= {'Access-Control-Allow-Origin': "*"},
body="test"
)
except Exception as ex:
return dict(
statusCode=500,
body=str(ex)
)
And this works, in Chrome's Network-Tab I see that we pass a post request and there is no issue, and the header is recognized properly, allowing Cross-Origin calls. But this is pretty much just the GET request I have which is already set up and working. So when I update it to be more similar to a POST METHOD and do what I want the problems begin.
So my code, that I want to be performed in the POST request is simple, I should be able to make the request like such,
def post(event, context):
try:
result=str(event.get("inputOne") + event.get("inputTwo"))
return dict(
statusCode=200,
headers= {'Access-Control-Allow-Origin': "*"},
body=result
)
except Exception as ex:
return dict(
statusCode=500,
body=str(ex)
)
When I test this in the AWS Lambda Management console, my code works, and I get the expected response back in the body.
But then when I try and call the POST endpoint from my React Site, I once again am getting the error:
Access to XMLHttpRequest at 'THE_POST_URL' from origin
'http://localhost:XXX' has been blocked by CORS policy: No 'Access-
Control-Allow-Origin' header is present on the requested resource.
So for some reason, when the body variable is not just a simple string in quotes like "this" <- it fails. I believe this has to do with the Content-Type in the request being of the form application/json;charset=UTF-8 while my request only accepts (as it says in dev-tools) application/json however even when trying to add the headers to accept this format for content-type, I am still getting the same issues.
I am not entirely sure why the header worked on the GET request, but not the POST request, and would appreciate anyone being able to help teach me, thank you!
EDIT: I have also tried adding 'Access-Control-Allow-Methods': "OPTIONS,GET,POST" to the headers of the post response, but this did not work either.
So after reading through the comments on my question, I decided it was worth going and taking a harder look at the way I had my API Gateway, and Lambda service set up on AWS.
I began using the curl utility in order to try and test my post-call from a terminal utility and found that there it was also failing, but I was able to use CloudWatch to debug, the issue and finally get it working.
The problem that I was facing with my curl Request was that I was not properly formatting the JSON input, but even when I was the Lambda was transforming the event improperly, not resulting in a Dict, as expected.
The curl call I was using can be seen:
curl -X POST https://myURL.execute-api.myREGION.amazonaws.com/stage/yourPOST \
-d '{"inputOne":80000,"inputTwo":85}'
But in order to read that input properly, and then work with it, I had to update my code in the Lambda to reflect parsing the input properly, this updated lambda code can be found here. The event object that you are passing to this lambda is a DICT object, so on the first line, we use JSON.loads to decode the "body" value of the event, into a dict that we store as body. Then to get the value of the two attributes, we use the command body.get("yourKey").
def yourPOST(event, context):
body=json.loads(event["body"])
a=body.get("inputOne")
c=body.get("inputTwo")
After making these changes the call from my React site works without error! If anyone has any questions feel free to comment, I hope this helped!
On a Network tab (Chrome browser) we can see a Headers tab.
Further if we have a request list we see General, Response Headers and Request Headers lists.
For example:
General:
Request URL: wss://some.url.com/websocket
Request Method: GET
Status Code: ...
Response Headers:
OWN-KEY-FROM-SERVER: true
etc...
If that was a XMLHttpRequest, we can use getAllResponseHeaders method of xhr, but WebSocket doesn't have something like this according to the WebSocket API.
I need to get from server some trigger and he is inside Responses Headers list.
Maybe somebody know a decision with that.
If using chrome is not the only option for you, then:
I used wireshark to manitor my websocket traffic. It included all the headers and bodies and works perfectly. Just set filter for tcp.port==YOUR_PORT || (websocket) and start manitoring.
I've a JS (Angular) client that makes a PUT request (REST API) to server and server sends back a large payload that I'm not using in the client currently.
Is there a way to just fire the request and ignore any response that comes back? The main need here is to avoid the data cost incurred by receiving that payload. I've looked at closing the connection once the request is fired, but am not sure if that's the best way to handle this.
If able, I think the only way to change this would be to change the api endpoint to not include a payload from the put request.
I'm assuming you are using angular's http class and using Observables. But even if you aren't, your angular client is going to need to read the response status sent back from the server to determine whether or not the put request was successful or not. In order to read the status, you'll need to response, and unfortunately the full response sent from the server.
You could close the connection right after the request, but as I've mentioned you'll have no way of knowing whether or not the request was successful.
To ignore the request just don't do anything if the request is successful.
If you don't want the request to exist at all then do it on the backend.
I'm performing the following $save which calls my angularJS $resource and POSTs to my API. I'm able to debug into my success callback handler and the object is actually created in my API.
myObj.$save({}, function (value, responseHeaders) {
myObj.someSuccessFunction();
}, function (responseText) {
myObj.someFailureFunction();
});
I'm unable to retrieve anything from the "responseHeaders" param. "responseHeaders()" returns an empty object. I would like to pull the "location" response header like this: responseHeaders("Location").
It's worth noting that the Response is filled in when debugging in chrome. The "responseHeaders" object is failing to be populated for some reason.
How can we get these responseHeaders?
Thanks!
Could it be a CORS issue? If you are making the call across a domain, be sure to include cors.exposed.headers in the pre-flight OPTIONS call.
If it is a cross domain call you have to add the following header in your response headers:
Access-Control-Expose-Headers: Location
With this, the browser is capable to expose your customs headers an read it angular.
I have the same issue with spring security 4.2 CORS filter and AngularJS. My client app built using Angular JS not able to read customer authentication token from response header sent by spring rest api.
I could resolve the issue by exposing below headers.
config.addExposedHeader("Origin");
config.addExposedHeader("X-Requested-With");
config.addExposedHeader("X-AUTH-TOKEN");
config.addExposedHeader("Content-Type");
config.addExposedHeader("Accept");
config.addExposedHeader("Authorization");
config.addExposedHeader("Location");
After the above fix. My Angular code able to read headers.
Trying to get the Request headers from the XHR object, but with no luck, is there a hidden method or property of that object that will expose the headers sent by the browser?
I already know how to set custom request headers and view the response headers, I'm looking to get a list of all REQUEST headers sent, ones created by the browser and my custom ones.
I'm using webkit/chrome, don't care about other browsers.
EDIT: I'm not looking to monitor the request, I'm building a web app and I need to list those headers and display them within the app, please don't tell me about fiddler, firebug and chrome tools, that's not what I'm looking for.
There is no method in the XMLHttpRequest API to get the sent request headers. There are methods to get the response headers only, and set request headers.
You'll have to either have the server echo the headers, or use a packet sniffer like Wireshark.
Try using Fiddler Web Debugger.
http://www.fiddler2.com/fiddler2/
You can capture the request that was sent in any browser as well as inspect the request headers, response headers, and even copy a capture sent request and send it out as your own.
Assuming you are using jQuery, and you're looking for anything attached, but maybe not ALL headers sent, this could help. Not sure if it meets your exact needs, (since the browser tends to add its own things), but if you need to grab your own headers first, this works:
$.ajaxSetup({
beforeSend: function (jqXHR, settings) {
if(!(settings.headers && settings.headers.token)) {
//no token header was set, so set the request header
jqXHR.setRequestHeader('token', newtoken);
}
}
})
As the name suggests, sent headers were SENT, (duh)! And the XMLHttpRequest class doesn't store sent headers in RAM or put sent headers in an instance of XMLHttpRequest... which is good for performance.
If you want to get the headers that have been sent, all you need to do is to create a log mechanism.
And since custom request header are created through XMLHttpRequest.prototype.setRequestHeader(), You need to intercept XMLHttpRequest.prototype.setRequestHeader();
var sentHeaders = {}
var originalXMLHttpRequest_setRequestHeader = XMLHttpRequest.prototype.setRequestHeader;
XMLHttpRequest.prototype.setRequestHeader = function(header, value) {
sentHeaders[header] = value;
originalXMLHttpRequest_setRequestHeader.call(this, header, value);
}
That's all. No need for external library nor Wireshark. All done within Javascript;
Just make sure the intercept code above executed before any XMLHttpRequest initialization.
Ps. this code will obviously only intercept the custom header created through setRequestHeader(). The XMLHttpRequest itself will set some default headers which can't be accessed through this method.