Reputation: 21
I would like to get access to the request headers sent in from WL client side. When I use this
var request = WL.Server.getClientRequest();
in the adapter procedure call, it returned null and causing the error on the line after
var userAgent = request.getHeader("User-Agent");
with error as: Cannot call method "getHeader" of null
Is there any special setup needed in order to use this WL api call?
Upvotes: 0
Views: 572
Reputation: 3166
It looks like adapter's invocation used in Studio is blocking the access to incoming client request. Basically speaking getClientRequest() is not working when you're using Eclipse's "Invoke Worklight Procedure" option. What you can do here is following - once you do "Invoke Worklight Procedure" a browser will open with URL similar to this
http://{serverIP}:{serverPort}/{projectName}/dev/invoke?adapter={adapterName}&procedure={procedureName}¶meters={params}
Remove /dev component from URL. So your URL will look like this
http://{serverIP}:{serverPort}/{projectName}/invoke?adapter={adapterName}&procedure={procedureName}¶meters={params}
This will make sure that adapter is invoked not via development preview but directly from WL server and getClientRequest() API will be fully functional.
P.S. You might hit a behaviour when "Invoke Worklight Procedure" is not opening an external browser window but instead showing the invocation result in Eclipse window. This depends on Eclipse version you're using and can be easily changed in Eclipse's preferences -> General -> Web Browser -> Use external web browser.
Upvotes: 0
Reputation: 3583
The API WL.Server.getClientRequest()
only works when invoked from a client (from a device or even from the preview) and not when invoked directly from Eclipse.
For example:
In the adapter XML I've created a procedure:
<procedure name="getUserAgent"/>
In the adapter JavaScript I've created a function called getUserAgent
that will return the userAgent to the client:
function getUserAgent() {
var request = WL.Server.getClientRequest(),
userAgent = request.getHeader("User-Agent");
return {userAgent : userAgent};
}
In the client Javascript I've created a function that is called from the wlCommonInit
. The function invokes the adapter procedure and the returned userAgent is displayed in an alert:
function wlCommonInit(){
getUserAgent();
}
function getUserAgent () {
WL.Client.invokeProcedure(
{
adapter: 'getClientRequest',
procedure: 'getUserAgent',
},
{
onSuccess : onSuccessGetUserAgent,
onFailure : onFailureGetUserAgent
}
);
}
function onSuccessGetUserAgent (data) {
alert('userAgent: ' + data.invocationResult.userAgent);
}
function onFailureGetUserAgent () {
alert('Failure');
}
Upvotes: 1