Why is my AJAX result not ETag-cached (no If-None-Match)? - http

Here is my AJAX function:
function ajax(url, data) {
return new Promise((resolve, reject) => {
$.ajax({
url: "https://xxx",
data: data,
method: 'POST',
timeout: 50000,
cache: true,
ifModified: true,
crossDomain: true,
success: (data, textStatus, jqXHR) => {
if (data == '#fail#') reject(data);
else {resolve(data);}
},
error: (jqXHR, textStatus, errorThrown) => {
reject(errorThrown);
}
});
});
}
As observed in Chrome -> Network(F12), this is the response header from the server:
HTTP/1.1 200 OK
X-Powered-By: Express
Access-Control-Allow-Origin: *
Content-Type: text/html; charset=utf-8
Content-Length: 3
ETag: W/"3-R7zlx09Yn0hn29V+nKn4CA"
Date: Fri, 06 Apr 2018 11:39:41 GMT
Connection: keep-alive
The request header is always identical, even in subsequent calls:
POST /register HTTP/1.1
Host: xxx:60001
Connection: keep-alive
Content-Length: 0
Accept: */*
Origin: http://localhost:8000
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36
Referer: http://localhost:8000/index.html
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Shouldn't Chrome, upon receiving an ETag header, cache the resource and set the 'If-None-Match' header on subsequent calls to the same URL? Shouldn't I obtain a status code of 304 instead of 200 as the returned content is the same?
The calls to the resources in other servers such as the Google Map server do return 304 sometimes though.

This confirms that caching is generally limited to GET request methods only:
However, common HTTP caches are typically limited to caching responses to GET and may decline other methods. The primary cache key consists of the request method and target URI (oftentimes only the URI is used as only GET requests are caching targets)
This is also confirmed in a post in StackOverflow here.

Related

Why Materialize template redirect from localhost to 127.0.0.1 after login?

I have added a custom login handler for Github:
const handleLoginGithub = (
params: LoginGithubParams,
errorCallback?: ErrCallbackType
) => {
axios
.get(authConfig.loginGithubEndpoint, { params })
.then(async (res) => {
/*window.localStorage.setItem(
authConfig.storageTokenKeyName,
res.data.accessToken
)*/
const returnUrl = router.query.returnUrl
setUser({ ...res.data })
await window.localStorage.setItem('userData', JSON.stringify(res.data))
//router.replace('/home')
})
.catch((err) => {
if (errorCallback) errorCallback(err)
})
}
There is no redirect from localhost to 127.0.0.1, but it will happen, do you know why?
This is the HTTP message that gos to our backend:
GENERAL:
Request URL: http://localhost:3000/api2/gh-auth-complete?code=f87f5157cbf035a73a50
Request Method: GET
Status Code: 200 OK
Remote Address: [::1]:3000
Referrer Policy: strict-origin-when-cross-origin
RESPONSE HEADER:
connection: close
content-length: 681
content-type: application/json; charset=utf-8
date: Sun, 09 Oct 2022 22:18:31 GMT
set-cookie: vapor-session=ReDSKZniIFtUqq0kThCkLbBe7vBoCpzpCUWqooA6xYQ=; Max-Age=31536000; Path=/; Secure; SameSite=Lax
Vary: Accept-Encoding
REQUEST HEADER:
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-GB,en-US;q=0.9,en;q=0.8
Connection: keep-alive
Host: localhost:3000
Referer: http://127.0.0.1:3000/
sec-ch-ua: "Chromium";v="106", "Google Chrome";v="106", "Not;A=Brand";v="99"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "macOS"
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: cross-site
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36
The reason why I am asking is, that in dev environment cookie will not be stored if it happens.

make flask return response header http1.1 instead http1.0 [duplicate]

I have a jQuery Ajax call, like so:
$("#tags").keyup(function(event) {
$.ajax({url: "/terms",
type: "POST",
contentType: "application/json",
data: JSON.stringify({"prefix": $("#tags").val() }),
dataType: "json",
success: function(response) { display_terms(response.terms); },
});
I have a Flask method like so:
#app.route("/terms", methods=["POST"])
def terms_by_prefix():
req = flask.request.json
tlist = terms.find_by_prefix(req["prefix"])
return flask.jsonify({'terms': tlist})
tcpdump shows the HTTP dialog:
POST /terms HTTP/1.1
Host: 127.0.0.1:5000
User-Agent: Mozilla/5.0 (X11; Linux i686; rv:12.0) Gecko/20100101 Firefox/12.0
Accept: application/json, text/javascript, */*; q=0.01
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Content-Type: application/json; charset=UTF-8
X-Requested-With: XMLHttpRequest
Referer: http://127.0.0.1:5000/
Content-Length: 27
Pragma: no-cache
Cache-Control: no-cache
{"prefix":"foo"}
However, Flask replies without keep-alive.
HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 445
Server: Werkzeug/0.8.3 Python/2.7.2+
Date: Wed, 09 May 2012 17:55:04 GMT
{"terms": [...]}
Is it really the case that keep-alive is not implemented?
The default request_handler is WSGIRequestHandler.
Before app.run(), Add one line,
WSGIRequestHandler.protocol_version = "HTTP/1.1"
Don't forget from werkzeug.serving import WSGIRequestHandler.
Werkzeug's integrated web server builds on BaseHTTPServer from Python's standard library. BaseHTTPServer seems to support Keep-Alives if you set its HTTP protocol version to 1.1.
Werkzeug doesn't do it but if you're ready to hack into the machinery that Flask uses to instantiate Werkzeug's BaseWSGIServer, you can do it yourself. See Flask.run() which calls werkzeug.serving.run_simple(). What you have to do boils down to BaseWSGIServer.protocol_version = "HTTP/1.1".
I haven't tested the solution. I suppose you do know that Flask's web server ought to be used for development only.

How to get http headers on a service in Jolie Programming Language

I have a service written in Jolie, where I want to extract the http headers on request. In the same way the request.id can be printed out, I would like to print the headers. There is a try on the bold letter down in the code. Here the code:
execution { concurrent }
inputPort UserDB_Service {
Location: "socket://localhost:8002/"
Protocol: http { .format = "json"}
Interfaces: Users, ShutdownInterface, ConnectionPool
}
outputPort DB_Connector {
Location: "socket://localhost:1000/"
Protocol: sodep
Interfaces: ConnectionPool
}
init
{
connectionConfigInfo#DB_Connector()(connectionInfo);
connect#Database(connectionInfo)()
}
main
{
//Example: http://localhost:8002/retrieve?id=1
[ retrieve(request)(response) {
query#Database(
"select * from users where user_id=:id" {
.id = request.id
}
)(sqlResponse);
println#Console( "You have requested the user_id: " + request.id)();
**println#Console( "Request Headers: " + response.format)();**
if (#sqlResponse.row == 1) {
response -> sqlResponse.row[0]
}
} ]
}
Thanks for the help.
I did not understand if you know which headers you want to have in the inbound request or if you just want to print the whole http message for debugging purposes. It is quick in both cases, I report both solutions :)
In the first case you can set the headers parameter of the http protocol for the inputPort to include in the request message also the content of a specific header, e.g.,
http {
.headers.format = "format";
}
and then you can inspect the value in the usual way
println#Console( request.format )()
In the second case, you can use
http {
.debug = true;
.debug.showContent = true
}
to see the log of all http requests and responses and their bodies.
These and further info on protocols and in particular the http protocol is in the documentation of the Jolie site.
I put the output here again. I wonder if it is possible to extract the "iv-user: g47257" header, which I have injected by using Fiddler. Thanks again for the help.
The headers are like this (better format).
INFO: [UserDB_crud.ol] [HTTP debug] Receiving:
HTTP Code: 0
Resource: /retrieve?id=1
--> Header properties
iv-user: g47257
accept-language: en-US,en;q=0.8,da;q=0.6,es;q=0.4
host: localhost:8002
upgrade-insecure-requests: 1
connection: keep-alive
cache-control: max-age=0
accept-encoding: gzip, deflate, sdch
accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp
,*/*;q=0.8
user-agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTM
L, like Gecko) Chrome/48.0.2564.116 Safari/537.36
You have requested the user_id: 1
mar. 10, 2016 2:30:44 PM jolie.Interpreter logInfo
INFO: [UserDB_crud.ol] [HTTP debug] Sending:
HTTP/1.1 200 OK
Server: Jolie
X-Jolie-MessageID: 0
Content-Type: application/json; charset=utf-8
Content-Encoding: gzip
Content-Length: 72
?V*H,..?/JQ?R*I-.Q?Q*-N-??♦
↑?(?%?"dRs‼3s?\►?????T♂ %??WE
mar. 10, 2016 2:30:44 PM jolie.Interpreter logInfo
INFO: [UserDB_crud.ol] [HTTP debug] Receiving:
HTTP Code: 0
Resource: /favicon.ico
--> Header properties
iv-user: g47257
referer: http://localhost:8002/retrieve?id=1
accept-language: en-US,en;q=0.8,da;q=0.6,es;q=0.4
host: localhost:8002
connection: keep-alive
cache-control: no-cache
pragma: no-cache
accept-encoding: gzip, deflate, sdch
user-agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTM
L, like Gecko) Chrome/48.0.2564.116 Safari/537.36
accept: */*
mar. 10, 2016 2:30:44 PM jolie.Interpreter logWarning
WARNING: [UserDB_crud.ol] Received a message for operation favicon.ico, not specified in the input port at the receiving service. Sending IOException to the caller.
mar. 10, 2016 2:30:44 PM jolie.Interpreter logInfo
INFO: [UserDB_crud.ol] [HTTP debug] Sending:
HTTP/1.1 200 OK
Server: Jolie
X-Jolie-MessageID: 0
Content-Type: application/json; charset=utf-8
Content-Encoding: gzip
Content-Length: 102
?VJ-*?/R??V?M-.NLOU?R??w?HN-(???S?QJ?O☺?→←↓↑↑?(?$?$???%?d?(?↨?▬%?¶Z)?%?e&???☺ ??Z ?yd?Y
I re-post my last comment here since other people faced the same difficulties found by Efrin but might miss the solution I posted as a comment.
You can inspect the headers of a HTTP request as shown in the code below
include "console.iol"
inputPort Me {
Location: "socket://localhost:8000"
Protocol: http { .headers.iv_user = "ivUser" }
RequestResponse: myRequest
}
main {
myRequest( request )(){ println#Console( request.ivUser )() }
}
Remember that, as reported in the documentation, Jolie http.headers parameters map - in header names with _, e.g., in your case, header iv-user becomes iv_user in the Jolie HTTP protocol parameters.
Besides the description and code found in the Jolie documentation, you can find further examples and a more thorough explanation on how the HTTP protocol works in Jolie in its presentation paper wrote by Montesi https://doi.org/10.1016/j.scico.2016.05.002.

Using AngularJS $http with asp.net webservice, is there a way to set the request headers?

I've just come across a bizarre issue with regards to retrieving data via asp.net webservice.
when using JQuery's ajax method the headers are set correctly and the data is retrieved in JSON successfully.
JSON example:
$.ajax({
type: "GET",
url: "service/TestService.asmx/GetTestData",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: callback,
error: function (err, xhr, res) {
alert(err);
}
});
The Request Headers for the above is the following:
Accept application/json, text/javascript, */*; q=0.01
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Content-Type application/json; charset=utf-8
Host localhost
Referer http://localhost/
User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0
X-Requested-With XMLHttpRequest
The Reponse Headers for above is the following:
Cache-Control private, max-age=0
Content-Length 327
Content-Type application/json; charset=utf-8
Date Tue, 29 Oct 2013 17:59:56 GMT
Server Microsoft-IIS/7.5
X-AspNet-Version 4.0.30319
X-Powered-By ASP.NET
this works fine.
But for AngularJS $http method the Request Headers Content-Type value is not set, therefore the Response Headers Content-Type defaults to text/xml; charset=utf-8. Have a look at the example below:
$http({
method : 'GET',
url: 'service/TestService.asmx/GetTestData',
headers: {
'Accept': 'application/json, text/javascript, */*; q=0.01',
'Content-Type': 'application/json; charset=utf-8'
}
}).success(callback);
The Request Headers for above is as follows, you will see that Content-Type is missing:
Accept application/json, text/javascript, */*; q=0.01
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Host localhost
Referer http://localhost/ComponentsAndRepos/
User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0
therefore the Response Headers for the above is the following:
Cache-Control private, max-age=0
Content-Encoding gzip
Content-Length 341
Content-Type text/xml; charset=utf-8
Date Tue, 29 Oct 2013 17:59:56 GMT
Server Microsoft-IIS/7.5
Vary Accept-Encoding
X-AspNet-Version 4.0.30319
X-Powered-By ASP.NET
therefore this forces the response to return as XML not JSON, is there a way to resolve this?
thank you,
Update
Thanks to Erstad Stephen
This has been resolved by adding data:{} property to $http method.
$http({
method : 'GET',
url: 'service/TestService.asmx/GetTestData',
data: {},
headers: {
'Accept': 'application/json, text/javascript, */*; q=0.01',
'Content-Type': 'application/json; charset=utf-8'
}
}).success(callback);
You can handle this a couple of different ways:
You can set the header defaults through the $httpProvider: http://docs.angularjs.org/api/ng.$http#description_setting-http-headers
You can also use the Interceptors in Angular to intercept the idea for $http to modify the config object for all requests: http://docs.angularjs.org/api/ng.$http#description_interceptors
You could also set the config setting like you are above.
The biggest thing is that you maybe misunderstanding how the config works. See this question here: Angular, content type is not being generated correctly when using resource

Why doesn't Chrome and Firefox send FormAuthentication cookie in Ajax request

I am using the following blob of jQuery to issue requests to a WCF Ajax enabled webservice
The site itself is hosted at localhost:80 and the WCF services at localhost:8080
$.ajax({
type: "POST",
url: String.format(Service, Method),
contentType: "application/json; charset=utf-8",
data: JSON.stringify(Data),
timeout: 6000,
dataType: "json",
success: function (e) { OnSuccess(e); },
error: function (e) { OnFailed(e); }
});
This works fine in IE but when I attempt to run this code in Chrome or Firefox (even after the user has been authenticated) I receive the error HTTP/1.1 401 Unauthorized. After running fiddler its clear why, as chrome is not sending the Cookie .ASPXFORMSAUTH that I have configured for forms authentication.
Specifically this is what the IE request looks like
POST /SchedulerService.svc/GetAllEventsByCurrentUser HTTP/1.1
Accept: application/json, text/javascript, */*; q=0.01
Content-Type: application/json; charset=utf-8
Referer: http://localhost/Calendar/Calendar.aspx
Accept-Language: en-AU
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)
Connection: Keep-Alive
Content-Length: 0
DNT: 1
Host: localhost:8080
Pragma: no-cache
Cookie: ASP.NET_SessionId=dmz5jv3oxa0llsph0thh1443; .ASPXFORMSAUTH=5EA7CB8124C5077933A639062999A89D35D440C6AD1A038C83A42D34694C20886506721D3CCD899BDA7B705CEF3B3024368AD6AE4523DEBDC5891E8DDD478206A3C2EF852345F70812F01D30F8F1041C2113EA2836CC5353FEAF81FC3EBF4DB6921D6DB270DE5C4102321DDD4D3923082B890995195990088749A1815B6A0BE5
VS CHROME
POST /SchedulerService.svc/GetAllEventsByCurrentUser HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 0
Accept: application/json, text/javascript, */*; q=0.01
Origin: http://localhost
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.94 Safari/537.36
Content-Type: application/json; charset=utf-8
Referer: http://localhost/Calendar/Calendar.aspx
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-AU,en;q=0.8,en-US;q=0.6,en-GB;q=0.4
Could anyone provide any guidance on what might be going wrong? I realize I may need to provide more information but not sure what else is relevant.
EDIT: Well after trying many, many different ideas it seems to me that all my problems likely stem from a drastic difference in implementation of the same origin policy between IE, Chrome and Firefox. Will update when I have more...
As your asp.net and wcf applications seem to be hosted on different ports (80 and 8080), you may give a try to beforeSend to send credentials :
$.ajax({
type: "POST",
url: String.format(Service, Method),
contentType: "application/json; charset=utf-8",
data: JSON.stringify(Data),
timeout: 6000,
dataType: "json",
success: function (e) { OnSuccess(e); },
error: function (e) { OnFailed(e); },
beforeSend: function(xhr){
xhr.withCredentials = true;
}
});
see https://stackoverflow.com/a/2054370/1236044

Resources