Search code examples
restxmlhttprequestnetsuitesuitescript

How to POST to NetSuite custom record from external site?


I'm trying to integrate a very small custom web application with NetSuite. I want a custom record to be created in NetSuite whenever a user clicks a button in my web application.

I have written a RESTlet that works with the REST API Testing chrome extension. I have successfully created records through that chrome extension.

However, when I try to POST from my web application, I get this error:

"Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 401."

How can I POST to NetSuite with a RESTlet from an external site? Should I even be using a RESTlet or is there a better way?


Solution

  • RESTlets are meant more as a system to system technology. They require authentication and if you are doing that from a public app your credentials will be compromised.

    Netsuite doesn't allow you to set a CORS header so your cross domain integration needs to be via a publicly available suitelet and JSONP.

    Since JSONP makes use of get requests you need to make sure your url params end up less than about 2k characters. That's not a standard limit so ymmv

    patterns I often use: Client code:

    var url = "public suitelet url from deployment screen";
        var params = {
            mode: 'neworder',
            //simple name/value data
        };
        $.ajax({
                url: url+"&"+ $.param(params) +"&jsoncallback=?",
                cache:false,
                dataType:'json',
                success: function(jResp){
                    if(!jResp.success){
                        if(jResp.message) alert(jResp.message);
                        return;
                    }
                    // act on the results
                }
        });
    

    A library function in the suitelet source file.

    function _sendJSResponse(request, response, respObject){
        response.setContentType('JAVASCRIPT');
        //response.setHeader('Access-Control-Allow-Origin', '*');
        var callbackFcn = request.getParameter("jsoncallback")  || request.getParameter('callback');
        if(callbackFcn){
            response.writeLine( callbackFcn + "(" + JSON.stringify(respObject) + ");");
        }else response.writeLine( JSON.stringify(respObject) );
    }
    

    and then a Suitelet function

    function service(request, response){
        ... do some work and generate a response
        var returnObj = {
            success:true,
            message: '',
            result:result
        };
    
        _sendJSResponse(request, response, returnObj);
    }