bootstrap-table how do I add a custom request header when using server pagination - bootstrap-table

I've been using bootstrap table (http://bootstrap-table.wenzhixin.net.cn/) successfully in a typescript project for quite some time.
Unfortunately due to the amount of data returned for one table I want to switch to using server side pagination for that table.
For the most part that seems reasonably straightforward but I need the table to pass a custom request header to the server and cannot see how to do that.
The current headers are as below but I need to get the bootstrap table to add in an authorisation header containing the auth token.
http://localhost/api/1.0/LotsofData?order=asc&offset=0&limit=15&_=1542242900391
Accept: application/json, text/javascript, */*; q=0.01
Accept-Encoding: gzip, deflate
Accept-Language: en-GB,en;q=0.5
Cache-Control: no-cache
Connection: keep-alive
Content-Type: application/json
Host: localhost
Origin: http://localhost:53391
Pragma: no-cache
Referer: http://localhost:53391/
User-Agent: {stuff}
How do I add the custom request header to the bootstrap-table's get request
Any assistance would be much appreciated.

Worked it out by searching for help on jquery $.ajax requests. You populate the ajaxOptions as shown in the code snippet.
...
url: controller.ourservice.build_url(scope.id1, scope.id2),
sidepagination: 'server',
ajaxOptions: { headers: { 'Authorization': 'Token ' + localStorage.getItem("access_token") }},
pageSize: 15,
pageList: [5, 15],
...

Related

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.

Spring REST Controller is not responding to Angular request

I have an app to create server certificate requests, just as if one were using java keytool or something. I'm trying to return the created certificate request and the key in a zip file, but for the life of me, I can't get my REST controller to respond to the http request. CORRECTION: The controller responds, but the code within the method is never executed.
The server does receive the request, because my CORS filter is executed. But I have a debug set in the controller method, and it's never triggered. Is the signature of the method correct? I need another set of eyes, please?
Here is my controller code:
#RequestMapping(method = RequestMethod.POST, value = "/generateCert/")
public ResponseEntity<InputStreamResource> generateCert(#RequestBody CertInfo certInfo) {
System.out.println("Received request to generate CSR...");
byte[] responseBytes = commonDataService.generateCsr(certInfo);
InputStreamResource resource = new InputStreamResource(new ByteArrayInputStream(responseBytes));
System.out.println("Generated CSR with length of " + responseBytes.length);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=certificate.zip")
.contentType(MediaType.parseMediaType("application/zip"))
.contentLength(responseBytes.length)
.body(resource);
}
And here is the Angular request:
generateCertificate(reqBody: GenerateCert) {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
this.http.post(this.urlGenerateCert, JSON.stringify(reqBody), {headers: headers}).subscribe(
(data) => {
let dataType = data.type;
let binaryData = [];
binaryData.push(data);
this.certBlob = new Blob(binaryData);
});
return this.certBlob;
}
And finally, the request and response headers I copied from the Network Panel:
Response
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Content-Type, Authorization, Accept, X-Requested-With, remember-me
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Origin: *
Access-Control-Max-Age: 3600
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Content-Length: 0
Date: Thu, 27 Dec 2018 22:48:00 GMT
Expires: 0
Location: http://localhost:8102/login
Pragma: no-cache
Set-Cookie: JSESSIONID=EDACE17328628D579670AD0FB53A6F35; Path=/; HttpOnly
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
Request
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 205
Content-Type: application/json
Host: localhost:8102
Origin: http://localhost:4200
Referer: http://localhost:4200/generateCerts
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.80 Safari/537.36
I really struggled with getting CORS working, so maybe that's interfering with the request? I hate to post all that code unless absolutely necessary. Anybody got any ideas?
Listing of request/response headers lack information on URL, method and most important response status code.
Seeing Location: http://localhost:8102/login among response headers I can guess that it could be 401 Unauthorized or anything else that redirects to the login page. Hence, if there is an auth filter in the filter chain, it may be a culprit.
The following request headers
Host: localhost:8102
Origin: http://localhost:4200
suggests that you are doing CORS and the CORS filter may be involved indeed and fulfill response before the request gets routed to the controller. I suggest setting a breakpoint into the CORS filter (and into others if any) and debug it to the point where the response is returned.
define a proxy.conf.json
{
"/login*": {
"target":"http://localhost:8080",
"secure":false,
"logLevel":"debug"
}
}
now in your package.json
"scripts": {
"start":"ng serve --proxy-config proxy.config.json"
}
I think there is issue while getting connection in both webapp.please try .
When Angular encounters this statement
this.http.post(url,body).subscribe(data => # some code
);
It comes back immediately to run rest of the code while service continues to execute. Just like Future in Java.
Here if you
return this.cert;
You will not get the value that may eventually get populated by the this.http service. Since the page has already rendered and the code executed. You can verify this by including this within and outside the Observable.
console.log(“Inside/outside observable” + new Date().toLocalTimeString());
Thanks to everyone who contributed. I discovered the error was due to the headers of my controller method. After changing them, the method was invoked properly. This is what worked:
#RequestMapping(method = RequestMethod.POST, path = "/generateCert",
produces = {MediaType.APPLICATION_OCTET_STREAM_VALUE}, consumes = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<byte[]> generateCert(#RequestBody CertInfo certInfo) {
byte[] responseBytes = commonDataService.generateCsr(certInfo);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE)
.contentLength(responseBytes.length)
.body(responseBytes);
}

Lua nginx extracting destination path from POST header

I am working on uploading files using nginx. I have installed openresty module to support ngx lua .While uploading files I need to change the upload_store variable to the path in the POST header received. So I am thinking of using lua to change upload_store directive value in nginx.conf. I am trying to get the Dst-Dir from header like below:
location /umtest {
set $upload_store /mnt/share_marvel/uploaded_files;
rewrite_by_lua '
local header = ngx.req.raw_header()
ngx.say("type header",header)
dst_path_dir = #need to extract from header
ngx.var.upload_store = dst_path_dir
ngx.say("upload store path" ,ngx.var.upload_store)
';
Header received from ngx.req.raw_header() is
POST /umtest HTTP/1.1
Host: X.X.X.X:8888
Connection: keep-alive
Content-Length: 0
Cache-Control: no-cache
Dst-Dir : "/path/to/upload"
Origin: chrome-extension://fhbjgbiflinjbdggehcddcbncdddomop
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9
How can I extract the value of Dst-Dir, so that i can set that value to upload_store? I am pretty new to lua.
Give a try to ngx.req.get_headers(), for example:
dst_path_dir = ngx.req.get_headers()["Dst-Dir"]

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

SignalR routing issue, get 200 ok but response empty

I have an existing MVC application which I am integrating a hub into, now I have setup the hub like so:
routeTable.MapHubs("myapp/chat/room", new HubConfiguration { EnableCrossDomain = true, EnableDetailedErrors = true, EnableJavaScriptProxies = true });
Then in the clientside I am connecting like so:
var connection = $.hubConnection(SystemConfiguration.ServiceUrl + "/myapp/chat/room", { useDefaultPath: false });
var hub = this.Connection.createHubProxy("ChatHub"); // Same name as on the hub attribute
connection.start().done(function(){ /* do stuff */});
Then I see the HTTP Request like so:
http://localhost:23456/myapp/chat/room/negotiate?_=1374187915970
Response Headers
Access-Control-Allow-Cred... true, true
Access-Control-Allow-Head... content-type, x-requested-with, *
Access-Control-Allow-Meth... GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Orig... http://localhost:34567, http://localhost:34567
Access-Control-Max-Age 10000
Cache-Control no-cache
Content-Length 420
Content-Type application/json; charset=UTF-8
Date Thu, 18 Jul 2013 22:52:18 GMT
Expires -1
Pragma no-cache
Server Microsoft-IIS/8.0
X-AspNet-Version 4.0.30319
X-Content-Type-Options nosniff
Request Headers
Accept application/json, text/javascript, */*; q=0.01
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Content-Type application/x-www-form-urlencoded; charset=UTF-8
Host localhost:23456
Origin http://localhost:34567
Referer http://localhost:34567/myapp/chat?chatId=1764a2e3-ff6f-4a17-9c5f-d99642301dbf
User-Agent Mozilla/5.0 (Windows NT 6.2; WOW64; rv:22.0) Gecko/20100101 Firefox/22.0
The response though contains no body, its got a 200 status though... I am debugging on the server and the hub methods are never hit. The only non standard thing in this scenario is that I have a custom CORS HttpModule which intercepts traffic and appends the CORS required headers, as you can see in the response, so not sure if this confuses SignalR's CORS support in some way. Anyway I can see the HttpModule being hit so it goes past there fine, but is somehow lost between there and the hub.
Tried googling but not much info on this topic...
The issue seems to be down to my CORS handling at HttpModule level, it must somehow conflict with SignalR... if I put a check in the module to see if the URL contains "chat/room" and just ignore the request if needed it then works fine, however it feels like a hack, but at least it works now.

Resources