Connect from Zendesk(javascript) to Acumatica(IIS) - javascript

I am trying to connect from Javascript to Acumatica with following code:
var xmlhttp = new XMLHttpRequest();
URL = "h ttps://demo.mytestwebsite.com/entity/auth/login/";
xmlhttp.open("POST", URL, false);
xmlhttp.setRequestHeader("Authorization", "Basic " + btoa("Admin:hgfjk"));
xmlhttp.send();
And getting error:
VM2372:7 OPTIONS https ://demo.mytestwebsite.com/entity/auth/login/ 405 (Method Not Allowed)
connect # VM2372:7
(anonymous) # VM2374:1
VM2372:7 XMLHttpRequest cannot load http s://demo.mytestwebsite.com/entity/auth/login/. Response for preflight has invalid HTTP status code 405
connect # VM2372:7
(anonymous) # VM2374:1
VM2372:7 Uncaught DOMException: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'http s://demo.mytestwebsite.com/entity/auth/login/'.
at connect (:7:15)
at :1:1

This issue is caused by CORS, i.e. the web browser does not get the necessary response from IIS hosting Acumatica, to satisfy CORS. CORS is a mechanism of increasing security in browsers.
When encountering this issue you can also run into these sorts of errors:
Response for preflight has invalid HTTP status code 500
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource
As of Acumatica Version 6.10.0945, this is how you configure IIS to make it CORS compatible for Acumatica for this type of requirement.
Add the following HTTP Response Headers within IIS.
Name: Access-Control-Allow-Origin Value: http://5.5.5.5 (IP Address or URL of the site that will connect to Acumatica - eg. https://mycompany.zendesk.com)
Name: Access-Control-Allow-Headers Value: Content-Type, cache-control
Name: Access-Control-Allow-Credentials Value: true
When values are added from Internet Information Services (IIS) Manager, they also appear in the web.config file in the Acumatica application folder as Custom Headers. For example - C:\Program Files (x86)\Acumatica ERP\MainAcumatica\web.config
I experienced issues adding the entries directly to web.config so suggest it is done through IIS.
Secondly, an entry needs to be made into the Global.asax file located in the same directory as web.config
This is the complete file with the function to insert being Application_BeginRequest():
<%# Application Language="C#" Inherits="PX.Web.PXApplication" %>
<script RunAt="server">
protected override void MergeAdditionalAssemblyResources()
{
PX.Web.UI.AssemblyResourceProvider.MergeAssemblyResourcesIntoWebsite<PX.Web.Controls.PXResPanelEditor>();
}
protected override void Initialization_ProcessApplication()
{
Initialization.ProcessApplication();
}
protected void Application_BeginRequest() {
if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS") {
Response.Flush();
}
}
</script>
The function Application_BeginRequest() in this file is flushing the response generated by the application for CORS OPTIONS requests, and letting IIS handle it with its header configuration.
OPTIONS requests are made by the CORS mechanism in the web browser, referred to as ‘pre-flight’, in order to confirm that the target server for the request is CORS compliant.
These settings will resolve the issue reported.

Instead of using basic authentication, try to pass username, password, company, branch, and locale (company, branch, and locale are optional) as request body following the sample below:
URL = "http://10.211.55.3/StackOverflow/entity/auth/login"; //Your URL
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", URL, false);
xmlhttp.setRequestHeader("Content-Type", "application/json");
var params = "{ name: '<username>', password: '<password>' }";
xmlhttp.send(params);

Related

Angular 13 request backend java interface, cross-domain error

Angular requested backend Spring boot Application to generate Excel's interface, and a cross-domain error occurred. But I've already done cross-domain processing on the back end, so what's going on?
Access to XMLHttpRequest at 'http://localhost:8080/api/ticket/myTicketDownload' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
#CrossOrigin
#GetMapping("/ticket/myTicketDownload")
public void myTicketDownload(HttpServletResponse response ) throws IOException {
response.reset();
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8");
String day = DateUtils.localDateformat(LocalDate.now());
String fileName = URLEncoder.encode("myTicket"+day, "UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
TicketQueryDto ticketQueryDto = new TicketQueryDto();
ticketQueryDto.setPkMyTicket("111");
List<TicketVo> allTicketData = iTicketGeneralService.getMyTicketData(ticketQueryDto);
EasyExcel.write(response.getOutputStream(), TicketVo.class).sheet(day).doWrite(allTicketData);
}
//Angular
ExportMyTicket(){
return this.http.get<void>(`http://localhost:8080/api/ticket/myTicketDownload`)
}
You can't configurate CORS on the client side. Adding headers doesn't change anything. You need to configurate it in the backend. There must be somewhere a collection of domains the backend accepts.

How to POST json data to the server? (CORS error)

My goal
I am doing .aspx file on Microsoft Visual Studio. What I expect is that the system will scan the QR code and then send the JSON data to the server side.
PS. I am using XMLHttpRequest to send the data.
What I Get
First I tried to pass it directly, it does not work so I check its status and readyStats, what it shows is 1(open) and 0(not initialized) (I am expecting 4(done) and 200(ok)) the responseText is null. I then inspected my browser (Google Chrome), the console shows an error "Access to XMLHttpRequest at 'https://website-A.aspx' from origin 'https://localhost:44371' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource."
What I tried
So I searched for solution on stack overflow, most of them says that I need to put in the header Access-Control-Allow-Origin:* to the server, but the problem is I do not have the control of the server but I do contacted them to change the code to try it out, end up Access-Control-Allow-Origin:* doesn't work so I looked for alternative. I tried to use plugin such as Moesif Origin & CORS Changer but it shows "Access to XMLHttpRequest at 'https://website-A.aspx' from origin 'https://localhost:44371' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.".
Below is my code:
function onScanSuccess(qrCodeMessage) {
...
var url = "https://Website-A.aspx";
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.open("POST", url);
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
console.log(xhr.status);
console.log(xhr.responseText);
}
};
//I hardcoded the data for testing
var data = {
"SOME_ID": "Value",
"SOME_TYPE": "Value",
"SOME_ID": "Value",
"SOME_AMT": "Value",
"SOME_AMT_CURRENCY": "Value",
"SOME_DESC": "Value",
...
};
xhr.send(data);
}
Is there anyway to solve this without changing the server side's code or bypassing the CORS?
I wish to solve this by modify the code in the same .aspx only, is it possible?
If my code ain't going to work, is there any other way to do it?
Any helps will be appreciated.
cors must be allowed on server side. your code looks ok.
sorry, i can't use the comment function yet

Access-Control-Allow-Origin Apache SVN endpoint

I would like to make a XmlHttp GET request from client Javascript to a Apache SVN endpoint and I'm facing the following error:
Failed to load http://IP_ADDRESS/svn/: Response to preflight request
doesn't pass access control check: No 'Access-Control-Allow-Origin'
header is present on the requested resource. Origin
'http://IP_ADDRESS:3000' is therefore not allowed access.
I've tried set the Header set Access-Control-Allow-Origin "*" in the following files and no success so far.
/etc/apache2/mods-available/dav_svn.conf (the configuration is inside this file)
.htaccess (inside the endpoint root folder)
I'm running out of ideias how to do it.
The Javascript request code:
var xmlhttp = new XMLHttpRequest();
// encodedData = ...
xmlhttp.open('GET', url, true);
xmlhttp.setRequestHeader("Authorization", "Basic " + encodedData);
xmlhttp.withCredentials = true;
xmlhttp.send();
What am I doing wrong?
Have you tried adding the address of the client instead of *?
Header set Access-Control-Allow-Origin "http://IP_ADDRESS:3000"
Also if it doesn't work I would suggest adding these other options:
Header set Access-Control-Allow-Credentials "true"
Header set Access-Control-Allow-Methods "POST,GET,OPTIONS,PUT,DELETE"
Header set Access-Control-Allow-Headers "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"

Adding a curl request into a serviceNow business rule (javascript)

IN SHORT:
How do I write a javascript code that can send an API PUT message to my flask server?
CONTEXT
I have a simple flask applications like as described here: http://flask-restful.readthedocs.io/en/0.3.5/quickstart.html
But I have added CORS capability by adding this to the top:
from flask import Flask
from flask_restful import reqparse, abort, Api, Resource
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
api = Api(app)
It is on a server at [server_ip]
There is a ticketing service applications called serviceNOW and they allow one to run simple javascript commands in their business rules.
They supply the context:
(function executeRule(current, previous /*null when async*/) {
})(current, previous);
And I want to add the functionality: curl http://[server_ip]:5000/todos/todo3 -d "task=something different" -X PUT -v
MAIN IDEA: I want to send API calls from the serviceNOW server to my flask server when a business rule is called
Using the chrome console while on the serviceNOW server page I have run the following code:
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "http://[my_server]:5000/todos/todo3", false);
xhttp.send();
And i get the error:
Mixed Content: The page at 'https://[serviceNOW instance]' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://[server_ip]:5000/todos/todo3'. This request has been blocked; the content must be served over HTTPS.
(anonymous) # VM1629:1
VM1629:1 Uncaught DOMException: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'http://[server_ip]:5000/todos/todo3'.
at <anonymous>:1:7
EDIT 1
I changed:
xhttp.open("GET", "http://[my_server]:5000/todos/todo3", false);
xhttp.send();
to
xhttp.open("PUT", "https://[my_server]:5000/todos/todo3", false);`
xhttp.send(JSON.stringify({ "task": "new task2"}));
and i get:
VM1698:1 OPTIONS https://[server_ip]:5000/todos/todo5
(anonymous) # VM1698:1
VM1698:1 Uncaught DOMException: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'https://[server_ip]:5000/todos/todo5'.
at <anonymous>:1:7
My server says:
code 400, message Bad HTTP/0.9 request type ('\x16\x03\x...more hex..')
?m?~)]?n??K...more stuf..?,?0̨̩????/5" 400 -
EDIT 2
This is my current code:
var xhttp = new XMLHttpRequest();
xhttp.open("PUT", "https://[my_server]:5000/todos/todo3", false);`
xhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhttp.send(JSON.stringify({ "task": "new task2"}));
This is my current console side error:
DOMException: Failed to execute 'send' on 'XMLHttpRequest': Failed to load
This is my current server side error:
code 400, message Bad HTTP/0.9 request type
This curl works:
curl http://[server_ip]:5000/todos/todo5 -d "task=something differentyea" -X PUT -v
EDIT 3
This is my current code:
var xhttp = new XMLHttpRequest();
xhttp.open("PUT", "https://[my_server]:5000/todos/todo3", true);`
xhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhttp.send(JSON.stringify({ "task": "new task2"}));
This is my current error:
OPTIONS https://[server_ip:5000/todos/todo6 net::ERR_SSL_PROTOCOL_ERROR
EDIT 4
This code works (note the http and not https):
var xhttp = new XMLHttpRequest();
xhttp.open("PUT", "http://[my_server]:5000/todos/todo3", true);`
xhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhttp.send(JSON.stringify({ "task": "new task2"}));
But I have to run it from a none https site.
Business Rules in ServiceNow execute server side. Prototyping your code in the browser console will not be helpful. Most importantly, XMLHttpRequest does not exist server-side.
To make HTTP calls from a Business Rule you must use the ServiceNow RESTMessageV2 API. See API Docs - RESTMessageV2 for usage information and example code.
Your code might look something like this:
var rm = new sn_ws.RESTMessageV2();
rm.setEndpoint('http://[my_server]:5000/todos/todo3');
rm.setHttpMethod('PUT');
rm.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
rm.setRequestBody(JSON.stringify({ "task": "new task2"}));
var response = rm.execute();
var responseBody = response.getBody();
// Process the response here...
response is a RESTResponseV2 object. See the docs for more information on interacting with the response.

Python Tornado: how do I set WebSocket headers?

I'm new to web development so let me explain:
I want my Python Tornado server to communicate with a web page. My web page uses WebSockets and the onmessage function to print what it should receive from the Tornado server. Basically, here is the HTML JavaScript part:
$(document).ready(function() {
var myURL = "http://localhost:8888";
var source = new EventSource(myURL, { withCredentials: true }); // Access-Control-Allow-Origin
...
source.onmessage = function(event) {
console.log("received new event!");
};
...
}); // ready()
I'm setting the withCredentials parameter to true so CORS are enabled.
On the Tornado side, I have a WebSocket class which is supposed to answer back, but I don't know how to set the header to have Access-Control-Allow-Origin enabled. Here is the tornado code:
class EchoWebSocket(tornado.websocket.WebSocketHandler):
def check_origin(self, origin):
return True
def on_message(self, message):
self.write_message(u"Received message: " + message)
def make_app():
return tornado.web.Application([ ('/', EchoWebSocket), ])
if __name__ == '__main__':
app = make_app()
app.listen(8888)
print 'listening on port 8888...'
# start main loop
tornado.ioloop.IOLoop.current().start()
I'm stuck with the following error in my browser!
GET http://localhost:8888/ [HTTP/1.1 400 Bad Request 1ms]
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8888/. (Reason: CORS header 'Access-Control-Allow-Origin' missing).
What am I missing???
Your javascript is using EventSource but your server is serving WebSockets. These are two completely different things. You need to change one of those to match the other.

Categories

Resources