Arun Sangal Arun Sangal - 1 year ago 253
Node.js Question

CURL - NodeJS Rest API call Imperva - [SyntaxError: Unexpected token <]

I have written a shell script code which is successfully adding a new OS Connection IP in Imperva system/instance.

## Create a new IP OS connection in a given site, server group.
echo -e "\n- Trying to create a new OS connection IP now.\n";

##Make sure while initiating a REST API call, any parameter which has ' ' (space) in Imperva should be substituted with '%20'.
##JSESSIONID will be generated first and will be available to this function
create_new_ip_output="$(curl -ik -X POST -H "Cookie: JSESSIONID=$JSESSIONID" -H "Content-Type: application/json" -H "Accept: application/json" "https://${MX}:8083/SecureSphere/api/v1/conf/serverGroups/${siteName// /%20}/${serverGroupName// /%20}/servers/${addThisIP}" -d '{"connection-mode":"SSH","host-name":"thisLinuxServer.fdqn","OS-type":"linux","user-name":"enter_your_userID"}')";
if [[ "${return_code}" == "0" && ! `echo "${create_new_ip_output}" | grep "do not have permission"` ]]; then
echo -e "\n\n- OS connection IP (${addThisIP}) created successfully in site: ${siteName}, servergroup: ${serverGroupName} and stdout:\n${create_new_ip_output}\n";
return 0;
echo -e "\n\n- Failed to create a new OS connection IP (${addThisIP}) in site: ${siteName} and servergroup: ${serverGroupName}\n- using session ID: ${JSESSIONID}, error log:\n${create_new_ip_output}\n";
return 1;

OK, the above code works fine and once run, I see valid output showing whether an IP got added successfully or what was the failure message.

Now, I'm trying to implement the same functionality in NodeJS.

To do that, I have successfully created functions to generate JSESSIONID (so that I can use it to perform multiple REST/API call operations, rather than creating a new session each time for any operation), successfully deleting a JSESSIONID (i.e. to logoff/out from Imperva session so that I don't hit the limit) and to successfully search an IP in Imperva system if it has been previously added.

Using the above shell script logic, I have written the following NodeJS code to add a new OS Connection IP in Imperva using Rest/API, but I'm getting an error.

//Imperva create IP
//qData is a hash array that has valid index/value pair values.
var impervaCreateIP = function(qData){
var deferred = Q.defer();
var data = ''
var options = {
hostname: '',
port: 8083,
method: 'POST',
path: '/SecureSphere/api/v1/conf/serverGroups/'+ qData['siteName'] + '/' + qData['serverGroupName'] + '/servers/' + qData['ip'],
headers: {
'Content-Type': 'application/xml',
'X-Requested-With': 'Nodejs',
'Cookie': 'JSESSIONID='+qData['sid']
//svtLog() is a logger that I'm using to log messages to a file. Out of scope of this post.
svtLog('info','Imperva','Inside impervaCreateIP function')
console.log('Inside impervaCreateIP')
httpHelp(options, data)
var result = JSON.parse(fullResponse[1])
console.log("11 -----")
console.log("22 -----")
svtLog('error','Imperva','Failed to add IP in Imperva')
return deferred.promise;

Error message:

Inside impervaCreateIP
{ hostname: '',
port: 8083,
method: 'POST',
path: '/SecureSphere/api/v1/conf/serverGroups/some%20Site%20NameInImperva/someServerGroupNameInImperva_01/servers/',
{ 'Content-Type': 'application/xml',
'X-Requested-With': 'Nodejs',
Cookie: 'JSESSIONID=7B3C378D365B673F6C749847DEDC7D8F } }
[SyntaxError: Unexpected token <]

I'm looking for 2 things:

1. How to resolve the error (as shown above).

2. How to pass CURL's -d option {...} body parameters in the NodeJS code above, like I used it in the shell script.

PS: Changing POST to GET (method), assures that the code is fine syntax wise as it successfully shows the IP (with GET operation) with the above NodeJS code.

So, it's failing only when I use POST (i.e. when I'm trying to create an IP) -vs- GET (which I use to find an IP exist or not). I checked as per the Imperva API doc, the response comes in JSON format. Not sure if due to missing bullet# 2 question, I'm getting this Syntax error with POST.

Answer Source


Solution to both bullet# 1 and #2 was to set the CURL "-d option values" in NodeJS like shown below (I was setting it blank earlier):

  var data = '{"connection-mode":"SSH","host-name":"thisLinuxServer.fdqn","OS-type":"linux","user-name":"enter_your_userID"}'

Now, both options and data will be sent to httpHelp(options,data) and it'll work.

The above is just an dummy data value. Usually I'd pass valid host-name in the JSON object.

Never thought that not setting the data variable would result in this syntax error.

Other thing, I was missing BIG time was the value for 'Content-Type' inside headers variable. That was the reason, the error message was having "<" bracket in it (as by default it looks for a <body>...</body> section containing some XML format but in our case, the HTML response contained or was getting returned in JSON { ... } format way for the body section. That's why it was showing an error for unexpected token <.

As per the API doc, it should have been "JSON" type, thus changed that line to

'Content-Type': 'application/json',
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download