Netsuite POST data from a Portlet to a RESTlet in JSON

4.7k views Asked by At

In NetSuite, I'm trying to create a form Portlet POST data to a RESTlet in JSON. I've checked the documentation and internet and all the examples I've been able to find are GET requests or they post to a backend Suitelet instead.

I've come to a point where I can make the request reach the RESTlet but it's not being formatted in JSON, so I get the following error:

Account: xxxxxxxxxxxxx
Environment: Production Date & Time: 6/11/2015 5:09 pm
Execution Time: 0.06s
Script Usage: 0
Script: gw_SS_FormBackend
Type: RESTlet
Function: postWMForm
Error: UNEXPECTED_ERROR
SyntaxError: Empty JSON string (null$lib#3)

I'm using the following code to set the submit button and it's working fine:

var headers = new Array();
headers['User-Agent-x'] = 'SuiteScript-Call';
headers['Authorization'] = 
    'NLAuth nlauth_account=' + cred.account + 
    ', nlauth_email=' + cred.email + 
    ', nlauth_signature=' + cred.password + 
    ', nlauth_role=' + cred.role;
headers['Content-Type'] = 'application/json';
portlet.setSubmitButton(nlapiRequestURL(getRESTletURL(), null, headers, 'POST'), 'Submit', '_hidden');

My problem is I don't know how to convert the form data to JSON before submitting it.

I'd appreciate any help.

2

There are 2 answers

1
YNK On

you can use JSON.stringify() function.

var headers = new Array();
headers['User-Agent-x'] = 'SuiteScript-Call';
headers['Authorization'] = 
'NLAuth nlauth_account=' + cred.account + 
', nlauth_email=' + cred.email + 
', nlauth_signature=' + cred.password + 
', nlauth_role=' + cred.role;
headers['Content-Type'] = 'application/json';
var myJsonHeader = JSON.stringify(headers);
portlet.setSubmitButton(nlapiRequestURL(getRESTletURL(), null, myJsonHeader, 'POST'), 'Submit', '_hidden');

Regards

0
bknights On

Why would you want to use a RESTlet? If you are in a portlet then you already have a valid NS session so you'd be better off using a Suitelet. A Suitelet you know is set up to handle JSON would be called thus:

nlapiRequestURL(suiteletURL', JSON.stringify{test:'it', when:new Date(), by:'Brett'}), {"content-type":'application/json'}, function(resp){console.log(resp.getBody());}, 'POST');

and your Suitelet code might include something like:

var body = request.getBody();

nlapiLogExecution('DEBUG', 'posted body', body);
var asJSON = JSON.parse(body);

var user = nlapiGetContext().getUser(); // system already knows who this is.
...
var obj = {
   success:true,
   stuff: asProcessed
};

response.setContentType('JAVASCRIPT');
response.writeLine( JSON.stringify(obj) );

Not quite as clean as a RESTlet but you avoid having to hack the credentials.