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.
Related
I'm using the following code to send files from a form to the server:
const request = new XMLHttpRequest();
const formElement = document.getElementById('form');
request.upload.addEventListener("progress", (e) => {
console.log("progress: " + e.loaded + "/" + e.total);
});
// request load handler (transfer complete)
request.addEventListener("load", function (e) {
console.log(e);
});
request.addEventListener("readystatechange", function (e) {
console.log(e);
});
// request error handler
request.addEventListener("error", function (e) {
console.log(e, request)
});
request.open("post", formElement.action);
request.responseType = "json";
request.send(new FormData(formElement));
The server may respond before reading the contents of the files in some condition, and I want to get that response and handle it on the client side.
But it seems that I only get an error event triggered (response with status 0, an empty status text of type json), and 2 readystatechange events with readystate 1 and readystate 4 (same empty response). if the server simply return a response without reading the contents.
I also don't see any response when looking at the POST request in the browser's dev tool (F12->Network tab->Respons)
With curl (curl -i -X POST -H "Content-Type: multipart/form-data" -F "data=blabla" localhost:5000/upload) I'm able to post and get the expected response, but not with XMLHttpRequest.
Any ideas of what I'm doing wrong?
I'm trying to make an Ajax POST request, but I keep getting a 404 error "GET https://www.test.com/login.aspx?ReturnUrl=%2fapi%2ftest%2fsave 404 (Not Found)"
Don't know if it is because the site has https?
This is the code I have used:
var params = { name: "Test"};
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://www.test.com/api/test/save', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
response = JSON.parse(xhr.responseText);
console.log(reponse);
}
};
xhr.send(JSON.stringify(params));
Any suggestions on how to make it work?
What is happening is that your backend / API is set up to require authentication and if a request is received without authentication, it redirects to the login page. You can see this in your error response:
"GET https://www.test.com/login.aspx?ReturnUrl=%2fapi%2ftest%2fsave 404 (Not Found)"
But the other problem is that you don't have a login page! So that explains the 404 Not Found response.
Either disable authentication on your API for testing, or include authentication / credentials in your Ajax request.
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.
What sort of situations could cause this handler to be called? I'm not finding any instance where this method throws an error.
I tried with the device offline, I get xmlHttpRequest.status = 0 but no error.
Question is what sort of situations can I create in order to test functionality of this handler.
var xmlhttp = new XMLHttpRequest(),
method = 'GET',
url = 'https://developer.mozilla.org/';
xmlhttp.open(method, url, true);
xmlhttp.onerror = function () {
console.log("** An error occurred during the transaction");
};
xmlhttp.send();
From: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequestEventTarget/onerror
Your question is the perfect example. Just try your code from your web developer console while on this very page.
Here, try it yourself:
var xmlhttp = new XMLHttpRequest(),
method = 'GET',
url = 'https://developer.mozilla.org/';
xmlhttp.open(method, url, true);
xmlhttp.onerror = function () {
console.log("** An error occurred during the transaction");
};
xmlhttp.send();
When dealing with any network based IO all kinds of things could happen. Cross-Origin requests are only one. What if the server is offline, DNS lookup fails, a router between you and the server that is critical point of failure goes down?
Since an XHR call is for a server response, onerror would come into play when there is an error at the server. Changing your client to be offline doesn't simulate a server error.
Suppose the server resource gets moved and the server responds with a 404 error? What if the server times out? What if the request itself is malformed and causes the server to throw an error?
I have a code like:
try{
...
} catch(error){
...
};
In try block, there is a function call that makes a request to a server. When there is no resource on the server, an error is raised (as I can see in Google Chrome's developers tool):
Failed to load resource: the server responded with a status of 404 (Not Found)
and I am trying to catch it in the catch block, but the error is not captured.
Is it a feature of JavaScript that load error is not captured by try catch block?
Typically, when requesting information from a server (for instance, via ajax, by setting the src of an img element, etc.), you don't get an exception, but you do get an error event or callback, not least because the code doing the request finishes before the request does, so it's impossible to throw an exception at that point. Since you haven't shown how you're requesting the information, it's impossible to be more specific, but this is why you're not getting an exception.
For instance, with an ajax request, if there's an error you see the ajax request complete but with the statusCode of the XMLHttpRequest object being an error status code, rather than 200. E.g.:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
// The request is complete; did it work?
if (xhr.statusCode >= 200 && xhr.statusCode < 300) {
// Yes
}
else {
// No, got a code outside the 2xx range
}
}
};
xhr.open("GET", "/your/url/here", true);
xhr.send();