Adding a curl request into a serviceNow business rule (javascript) - 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.

Related

Ebay Trading API Get Item Ajax Request

I want to made simple post request on Ebay trading api with javascript Ajax. Here is the call format. I got some error on the following request. can anyone tell me the what wrong with the call .
const findbtn = document.querySelector(".find-item-btn");
findbtn.addEventListener("click", getData);
function getData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
console.log(this.responseText);
};
const xml =
'<?xml version="1.0" encoding="utf-8"?>' +
'<GetItemRequest xmlns="urn:ebay:apis:eBLBaseComponents">' +
"<ErrorLanguage>en_US</ErrorLanguage>" +
"<WarningLevel>High</WarningLevel>" +
"<ItemID>232789363104</ItemID>" +
"</GetItemRequest>";
xhttp.open("POST", "https://api.ebay.com/ws/api.dll", true);
xhttp.setRequestHeader("X-EBAY-API-COMPATIBILITY-LEVEL", "967");
xhttp.setRequestHeader("X-EBAY-API-DEV-NAME","6cfe5ebb-73c4-465b-ad24-c4f0aea8de0");
xhttp.setRequestHeader("X-EBAY-API-APP-NAME","RegnantC-SaveWix-PRD-3ef66784f-24730a7");
xhttp.setRequestHeader("X-EBAY-API-CERT-NAME","PRD-ef66784f85c1-6c65-4919-bc83-24c6");
xhttp.setRequestHeader("X-EBAY-API-CALL-NAME", "GetItem");
xhttp.setRequestHeader("X-EBAY-API-SITEID", "0");
xhttp.setRequestHeader("Content-Type", "text/xml");
xhttp.setRequestHeader("Access-Control-Allow-Origin", "*");
xhttp.setRequestHeader("Access-Control-Allow-Headers","X-Requested-With, Origin, Content-Type, X-Auth-Token");
xhttp.setRequestHeader("Access-Control-Allow-Methods","GET, PUT, POST, DELETE");
xhttp.setRequestHeader("X-EBAY-API-IAF-TOKEN","v^1.1#i^1#f^0#r^0#p^3#I^3#t^H4sIAAAAAAAAAOVYeWwUVRjv9lJEaIigTUWzTiEeOLtz7e7sh"
);
xhttp.send(xml);
}
and got the following error
1 Access to XMLHttpRequest at 'https://api.ebay.com/ws/api.dll' from origin 'localhost/app' 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.
2 POST https://api.ebay.com/ws/api.dll net::ERR_FAILED
Please help me. is the right format for the ajax request
Actually it's causing the CORS error. You can read about it details from here https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
And if you want to overcome this issue you can enable CORS from server. I mean send the request through your server.
Or you can also use CORS anywhere header.
const corsHeader = "https://cors-anywhere.herokuapp.com/";
then use this corsHeader appending with your url like this,
xhttp.open("POST", corsHeader+"https://api.ebay.com/ws/api.dll", true);
It'll send the request and currently it's showing error: IAF token supplied is invalid. If you provide proper IAF token then it'll provide you the data.
I'm very new to programming in general so this will not be a technical answer in the least, but.... I did get this to eliminate the CORS error.
const corsHeader = "https://cors-anywhere.herokuapp.com/";
xhttp.open("POST", "https://api.ebay.com/identity/v1/oauth2/token", true);
xhttp.open("POST", corsHeader, true);
I had to go here first and enable temporary access though.
https://cors-anywhere.herokuapp.com/corsdemo
Now when I run this the console is saying:
"This API enables cross-origin requests to anywhere."
If I can figure out how to get any farther I will update this thread.

Connect from Zendesk(javascript) to Acumatica(IIS)

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);

Accessing Dropbox app from browser

I'm trying to test connecting to a Dropbox app (created on my account) from a web page running on localhost. I've chosen to generate an authorization code rather than using the redirect. It seems that any code that's generated and displayed on the code page (https://www.dropbox.com/1/oauth2/authorize_submit) produces an error in the console when I try to access the app folder's metadata:
window.open('https://www.dropbox.com/1/oauth2/authorize?client_id=<appId>&response_type=code');
POST https://api.dropboxapi.com/1/metadata/auto/ 401 (Unauthorized)
DropboxCloud # DropboxCloud.js:8
(anonymous) # MainWindowStandalone.js:45
DropboxCloud.js:10 {"error": "The given OAuth 2 access token doesn't exist or has expired."}
However, if I use an authorization code generated on the Dropbox app page I a can successfully reach the folder :
DropboxCloud.js:10 {"hash": "68a0fc8c0c5670ff10e8e98b7fefcde8", "thumb_exists": false, "bytes": 0, "path": "/", "is_dir": true, "icon": "folder", "root": "app_folder", "contents": [], "size": "0 bytes"}
My code:
var request = new XMLHttpRequest();
const url = 'https://api.dropboxapi.com/1/metadata/auto/';
request.open('post', url, true);
request.setRequestHeader('Authorization', 'Bearer ' + accessToken);
request.setRequestHeader('Content-Type', 'application/json');
request.send();
request.onload = () => {
console.log(request.response);
};
I'd like to grant others access using the code generation page to help me test my app. What else do I need to make it work?
The issue here is that "authorizations codes" are not the same as "access tokens", and cannot be used interchangeably.
When you retrieve a token using the OAuth 2 "token" flow, or via the "Generate" button on the app's page on the App Console, that gives you an actual Dropbox API OAuth 2 access token. That can be used to make API calls, such as to /1/metadata.
The string you get back from /oauth2/authorize when you use the OAuth 2 "code" flow is only an authorization code. That can't itself be used to make API calls. It is a temporary code that you can exchange for an access token, using /oauth2/token.
(Also, note that Dropbox API v1, such as /1/metadata, is deprecated.)

XHR Post Response 200 but Failed to Execute Send

I am having an issue with a post to an Api.
The Api is using OAuth, I am generating all the valid information and posting it to the request_token url.
In Chrome Network tab I get a response 200 with the correct token in response,
but in the console I get an error and cannot get the response data.
NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'https://www.obsidianportal.com/oauth/request_token'.
If I set it to Async then it fails outright with a POST (cancelled)
xhr.open("POST", "https://www.obsidianportal.com/oauth/request_token", false);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
//xhr.responseType = "text/html";
//xhr.responseType = "text";
xhr.addEventListener("error", function() { console.log(xhr, arguments); }, false);
xhr.send(postData);
PostData is the generated OAuth information which is only valid once, so it is hard to debug.
Any help on this issue would be great.

Getting Access Denied Error

Getting Access Denied Error on https in IE. while executing ajax call (to my server1) response which has another ajax call While my Ajax call url is on http .By implementing cors I able to execute on http.Tried JSONP also but then it execute my response till it find another ajax call .How to solve ?
below is on myserver1
alert('aaa');
var xhr2 = new XMLHttpRequest();
xhr2.open('GET', 'http://myserver2.com', true);
xhr2.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr2.send();
xhr2.onload = function () {
alert('fff');
var appCreds = xhr2.responseText;
alert(appCreds);
};
alert('xxx');
In addition to the trusted site requirement I found that the problem was not fixed until I used the same protocol for the request as my origin, e.g. my test site was hosted on a https but failed with any destination using http (without the s).
This only applies to IE, Chrome just politely logs a warning in the debug console and doesn't fail.

Categories

Resources