When using the frontend, it is not possible to post the request to the Netsuite backend directly. To overcome this limitation, we can utilize the xdomain library. When attempting to post the request from frontend to the Netsuite backend using Axios, it gets rejected by the Netsuite server. Therefore, we can use the xdomain library to accomplish this task.
Step 1:
We need to create an HTML file the code is added below
<!DOCTYPE HTML><script src="//unpkg.com/xdomain@0.8.2/dist/xdomain.min.js" master="domain URL of webapp"></script>
Step 2:
We need to create a Suitelet that returns the HTML file added earlier.
/**
* @NApiVersion 2.x
* @NScriptType Suitelet
*/
define(['N/file', 'N/log'],
function(file, log) {
function onRequest(context) {
try {
// Specify the internal ID of your HTML file in the NetSuite File Cabinet
var fileId = 1234; // Replace with the actual internal ID
// Load the HTML file using internal ID
var htmlFile = file.load({ id: fileId });
// Get the content of the HTML file
var htmlContent = htmlFile.getContents();
// Set the response content type to HTML
context.response.headers['Content-Type'] = 'text/html';
// Write the HTML content to the response
context.response.write(htmlContent);
} catch (e) {
// Log any errors
log.error({
title: 'Error in Suitelet',
details: e.toString()
});
// Set the response content type to plain text
context.response.headers['Content-Type'] = 'text/plain';
// Write an error message to the response
context.response.write('An error occurred while processing the request.');
}
}
return {
onRequest: onRequest
};
}
);
To need to add the code in the layout.js of the project folder.
<script src="//unpkg.com/xdomain@0.8.2/dist/xdomain.min.js" script slave="https://2400273.extforms.netsuite.com/app/site/hosting/scriptlet.nl?script=641&deploy=1&compid=2400273&h=169bf9782f5e63572194" async />
The slave is the suitelet URL
Then we can possibly post the request.The sample code is added below
var xhr = new XMLHttpRequest();
xhr.open("POST", process.env.NEXT_LOGIN_API_URL + query);
xhr.onreadystatechange = function(e) {
if (xhr.readyState === 4) console.log("got result: ", xhr.responseText);
};
xhr.send();
//or if we are using jQuery...
$.get(process.env.NEXT_LOGIN_API_URL + query).done(function(data) {
});
$.ajax({
url: process.env.NEXT_LOGIN_API_URL + query,
type: "POST",
data: JSON.stringify(data),
success: function(data) {
console.log("got result: ", data);
}
});