XMLHttpRequest error on send - javascript

i'm doing my baby steps in web-development.
I have a Html+JS(jQuery) Frontend and a C# Backend.
For now i just want a ping-pong request/response.
The JS looks like this :
$(document).ready(function() {
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", "http://testhttp/", false ); // false for synchronous request
xmlHttp.send();
console.log(xmlHttp.responseText);
});
The C# looks like this
if (!HttpListener.IsSupported)
{
...
}
string[] prefixes = {"http://testhttp/"};
// Create a listener.
HttpListener listener = new HttpListener();
// Add the prefixes.
foreach (string s in prefixes)
{
listener.Prefixes.Add(s);
}
listener.Start();
Console.WriteLine("Listening...");
// Note: The GetContext method blocks while waiting for a request.
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
// Obtain a response object.
HttpListenerResponse response = context.Response;
// Construct a response.
string responseString = "<p> Hello world!</p>";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
// Get a response stream and write the response to it.
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer,0,buffer.Length);
// You must close the output stream.
output.Close();
listener.Stop();
The Backend receives the request. However the response will not be transmitted correctly or permission is denied (on Firefox and Chrome).
jquery-3.2.0.min.js:2 Uncaught DOMException: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'http://testhttp/'.
I read that it might has something to do with the origin of the response and i need to set Access-Control-Allow-Origin. But those attempts failed.
Can someone pls guide me here?
Edit
Based on comments the js looks like this
$(document).ready(function() {
$.ajax({
url: "http://testhttp/",
type: "GET",
crossDomain: true,
dataType: "json",
success: function (response) {
$('#Test').html(response);
},
error: function (xhr, status) {
alert("error");
}
});
});
and in C# backend i added
response.Headers["Access-Control-Allow-Origin"] = "*";
Getting
GET http://testhttp/ net::ERR_CONNECTION_RESET

Related

Ajax url is undefined

I'm making a function to get a xml file and edit it. I've never done that before so I searched a good way to get an xml file. I decided to use ajax, but the file is never returned because the url is undefined.
EDIT :
I edited the code and made the treatment in the success function. Now there is no problem with this file.
Here is the update of the ajax part :
$.ajax({
type: 'GET',
url: 'allrtp.xml',
dataType: 'xml',
success: function(xml) {
//file = $.parseXML(xml);
// Editing the file to have the good dates
$(xml).find('StartDateTime').text(start);
$(xml).find('EndDateTime').text(end);
var strFile;
if (window.ActiveXObject) {
strFile = xml.xml;
} else {
strFile = (new XMLSerializer()).serializeToString(xml);
}
var encoded64 = Base64.encode(strFile); // Encoded in base64
var encodeURL = encodeURIComponent(encoded64); // Encoded URL
var AR = urlAR + encodeURL; // The URL to open
window.open(AR, '_blank');
}
})
Now all is working well about the xml file, I have a little problem with the window.open, which open my url but with %31 at the beggining, but it's another problem.
Thank you for your help !
file is undefined because you are declaring it inside a ajax success function
function openRecords(start, end) {
// Extraction of the xml file
var file;
$.ajax({
type: 'GET',
url: 'allrtp.xml',
dataType: 'xml',
success: function(xml) {
file = $.parseXML(xml);
},
error: function(ex) {
console.log(ex);
}
})
// Test
var start = '2016-02-15T12:57:00+01:00';
var end = '2019-02-16T13:57:00+01:00';
setTimeout(function(){
// Editing the file to have the good dates
file.find('StartDateTime').text(start);
file.find('EndDateTime').text(end);},1500);
}
Add an error callback:
error: function (ex) {}
Many things can be happening, you will get more info with the error callback. Probably you are querying an incorrect url. Do not trust that undefined upon url, see what returns your jquery ajax function. Maybe you should be querying something like '\files\xxx.xml'.
can you give me a picture of Network in your broswer? I want to know the URL is send or not:
1. F12 open your console
2. select the Network tab
3. refresh the broswer
4. check the request is send or not

Error in HTTP GET Request with gadgets.io.makeRequest

Sorry but I spent a half a day practicing first with gadgets.io.makeRequest, and can not understand why the request response contains an error. The code is Javascript working as OpenSocial gadget:
requestURI = "https://jazz.server.com:9443/rm/views?projectURL=https%3A%2F%2Fjazz.server.com%3A9443%2Frm%2Fprocess%2Fproject-areas%2F_FvrWIG3nEeexYJvvGxVsZg&oslc.query=true&oslc.prefix=rt=<https://jazz.server.com:9443/rm/types/>&oslc.select=rt:_W0SGoW3nEeexYJvvGxVsZg";
makeGETRequest(requestURI);
...
function makeGETRequest(url) {
try {
var params = {};
params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;
params[gadgets.io.RequestParameters.HEADERS] = {
"Accept" : "application/rdf+xml",
"OSLC-Core-Version": "2.0"
}
gadgets.io.makeRequest(url, function(obj) {
console.log("===== HTTP REQUEST START =====");
console.log("Method : GET");
console.log("URL : " + url);
console.log("Response : " + obj.text);
console.log("====== HTTP REQUEST END ======");
}, params);
}
catch(err) {
console.log("Can not perform HTTP request because of error: " + err.message);
}
};
When I do the same request with REST Client in Firefox, everything works properly. But if I do that with the code above, then I get an error in the log (abbreviated):
===== HTTP REQUEST START =====
common.js:311 Method : GET
common.js:312 URL : https://jazz.server.com:9443/rm/views?projectURL=https%3A%2F%2Fjazz.server.…roject-areas%2F_FvrWIG3nEeexYJvvGxVsZg&oslc.query=true&oslc.prefix=rt=<https://jazz.server.com:9443/rm/types/>&oslc.select=rt:_W0SGoW3nEeexYJvvGxVsZg
common.js:313 Response : {"errorMessage":"Illegal character in query at index 178: https://jazz.server.com:9443/rm/views?projectURL=https%3A%2F%2Fjazz.server.com%3A9443%2Frm%2Fprocess%2Fproject-areas%2F_FvrWIG3nEeexYJvvGxVsZg&amp;oslc.query=true&oslc.prefix=rt=<https://jazz.server.com:9443/rm/types/>&oslc.select=rt:_W0SGoW3nEeexYJvvGxVsZg","errorClass":"java.lang.IllegalArgumentException","errorTrace":["java.net.URI.create(URI.java:871)","org.apache.http.client.methods.HttpGet.<init>
...
common.js:314 ====== HTTP REQUEST END ======
I tried to replace greater and less symbols by their hex values but there's no result. And there's no ideas currently.
May be somebody could make a fresh sight to the code and define the problem on the fly. Help me please, I'm at a dead end.
Thank you very much in advance for any advice!
The error in your Response indicates the Java system on the server side can't create a valid URI from your query. Therefor it throws back an error
My best guess would be the dot just before query=true in oslc.query=true. And therefor all following uses of oslcDOT .
From RFC 1738 specification:
Thus, only alphanumerics, the special characters "$-_.+!*'(),", and reserved characters used for their reserved purposes may be used unencoded within a URL.
I discovered that gadgets.io.makeRequest isn't very stable as I would like to expect. May be I do some wrong but sometimes this function completes without any feedback and without starting the response function in the parameters. I changed to next code:
function makeGETRequest(urlValue) {
try {
$.ajax({
url: urlValue,
type: 'GET',
dataType: 'text',
headers: {
'Accept': 'application/rdf+xml',
'OSLC-Core-Version': '2.0'
},
success: function (result) {
var data = result;
},
error: function (error) {
console.log("Can not perform HTTP request because of error: " + error.message);
}
});
}
catch(err) {
console.log("Can not perform HTTP request because of error: " + err.message);
}
};
And there's no problem!

Asp / ajax call web service and GET xml

My code returns : interne server error
var parameters = "<?xml version='1.0' encoding='utf-8'?>" +
"<soap:envelope xmlns:xsi='ttp://www.w3.org/2001/xmlschema-instance' xmlns:xsd='http://www.w3.org/2001/xmlschema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>" +
"<soap:body>" +
"<listeVille xmlns='http://..../b1'>" +
"<ville>"+ "Test" +"</ville>" +
"</listeVille>" +
"</soap:body>" +
"</soap:envelope>";
$.ajax({
type: "POST",
url: _URL_SITE + "webservices/b1.asmx",
dataType: "xml",
data: parameters,
contentType: "application/soap+xml; charset=utf-8",
headers: {
Accept: '*/*',
SOAPAction: 'http://.../webservices/b1/ListeVille' },
success: function (xml) {
alert('test');
//var _xmldoc
//_xmldoc = new activexobject("microsoft.xmldom");
//_xmldoc.async = "false";
//_xmldoc.loadxml(xml);
},
error: function () {
alert('error');
}
});
And my web service :
<WebMethod(True)> Public Function ListeVille(ByVal ville As String) As System.Xml.XmlDocument
Dim _xml As System.Xml.XmlDocument = New System.Xml.XmlDocument
Dim _hsh As New ParameterCollection
Try
_hsh.Add("#Ville", "")
_xml.LoadXml(_hsh)
Catch ex As Exception
AjoutJournal(ex)
End Try
Return _xml
End Function
I try to call my web service and get a xml file.
For information, don't focus on my function ListeVille, it returns the great value.
Thanks!
You are getting an Internal Server Error which means that there is an Exception in your server Side Code.
If you enable the Remote Errors then you can see the errors on the remote machine. Otherwise, if you debug the code on the machine, you can see the exception Details.
Moreover, the usage of XmlDocument.LoadXml Method doesn't seem to be correct as posted in your question. The Parameter to the LoadXml is a String containing the XML document to load. Try to pass in a valid XML. You can find more details on msdn here

NodeJS - how to tell the nodeJS server to send not as chunked transfer? so that Ajax can receive it

I have a data coming to NodeJS and then it needs to be served to Ajax query. but because the NodeJS is transfering it as chunked data, none of the general Javascript/JQuery ajax methods are able to capture the packet.
How can i get the values
nodeJS:
http.createServer(options, (req, res) => {
msg = c++_to_javascript();
res.writeHead(200);
res.end(msg);
}).listen(89);
Javascript/JQuery:
received the data as transfer encoded: chunked as a result no methods are able to decode the received packets in JS.
How could i solve it from NodeJS or in JS?
TRY 1: FAILED
$.stream(javascript_to_c++,{
open:function(){
console.log("opened");
},
message:function(event){
console.log(event.data);
buf1 = buf1 + event.data;
},
error:function(){
console.log("error");
},
close:function(){
console.log("closed");
}
});
TRY2 : FAILED
var test = $.ajax({
type: "GET",
url: javascript_to_c++,
async: false,
success:function(m) {
buf1 = buf1 + m;
}
}).responseText;
console.log(test);
TRY 3: FAILED
// Define a method to parse the partial response chunk by chunk
var last_index = 0;
function parse(xhr) {
var curr_index = xhr.responseText.length;
if (last_index == curr_index) return; // No new data
var s = xhr.responseText.substring(last_index, curr_index);
last_index = curr_index;
console.log(s);
}
function test() {
var xhr = new XMLHttpRequest();
var url = javascript_to_c++;
xhr.open("GET", url, true);
xhr.send();
// Check for new content every 5 seconds
var interval = setInterval(parse, 5000);
// Abort after 25 seconds
setTimeout(function(){
clearInterval(interval);
parse(xhr);
xhr.abort();
}, 25000);
}
test();
You just have to properly wait for the response to come back. I'm not too familiar with the other ajax methods you're using but let's look at this for example:
var test = $.ajax({
type: "GET",
url: javascript_to_c++,
async: false,
success:function(m) {
buf1 = buf1 + m;
}
}).responseText;
console.log(test);
Are you expecting test to be the response? $.ajax returns a Promise representing the asynchronous request. It's not until the success callback is called or the promise is resolved when you'll get the response text. Try this instead:
var test = $.ajax({
type: "GET",
url: javascript_to_c++, // I'm assuming this is a valid URL?
success:function(content) {
console.log(content); // This is your actual full response.
}
});
As far as having the node process specify the content type, try the content-type header:
res.set('content-type', 'text/plain');
res.end(msg);
Update:
As already pointed out, it's highly doubtful that the Transfer-Encoding thing is actually a problem. It you do want to disable it, do:
res.set('transfer-encoding', '');
...but really, it shouldn't be necessary.
Another Update:
Not using Express? You'll just need to slightly modify this:
res.writeHead(200, {
'content-type': 'text/plain',
'transfer-encoding': '' // not recommended...
});
res.end(msg);

POST using jQuery AJAX in HP servicemanager (HPSM)

I know this is a long shot, but I'm trying to make a POST with AJAX within the Javascript tool in HPSM. It's got very limited debugging capabilities so I'm stuck where it should be simple (or so I thought). From the syntax I've seen in other articles, calling that AJAX function should be right, but it doesn't seem to want to take it.
Thanks for any help
Here is the code I'm calling, and using jQuery library v1.11.2
var JSONdata = {
"eId": "xxx111",
"deviceToken": "111111111111",
"deviceType": "iphone",
"applicationName": "huds"
};
system.library.jQuery.ajax({
type: "POST",
url: 'http://place:11400/location/collaboration/notifications/register/',
data: JSONdata,
dataType: "json",
cache: false,
crossDomain: true,
processData: true,
success: function (data) {
alert(JSON.stringify(data));
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("error");
}
});
errors
Process panel calc.javascript in RAD format.cjavascript encountered error in line 5 (format.cjavascript,calc.javascript)
Cannot evaluate expression (format.cjavascript,calc.javascript)
Cannot evaluate expression (format.cjavascript,calc.javascript)
Cannot evaluate expression (format.cjavascript,calc.javascript)
Cannot evaluate expression (format.cjavascript,calc.javascript)
Script <UNKNOWN> line 20: ERROR TypeError: system.library.jQuery.ajax is not a function at char 1
Script 'jQuery' line 925: ERROR TypeError: document has no properties at char 1
Unrecoverable error in application: se.call.process on panel call.rad.1
Unrecoverable error in application: cm.update.save on panel call.master.upd
Unrecoverable error in application: format.cjavascript on panel calc.javascript
I'm assuming you have a ScriptLibrary called jQuery in your HPSM, right?
Try with
lib.jQuery.ajax(...
instead of system.library, regards.
not sure if you have imported the jQuery as a ScriptLibrary, but I think it will not work, because the code inside the jQuery Library includes some lines of code which are not valid for the HPSM.
Anyway...
To call an external external RESTful Service, you can use the doHTTPRequest() function in your ScriptLibrary.
What it is, what parameters are needed etc. can be found in the Programming Guide:
http://86.48.81.222:6080/classic/Content/Resources/PDF/sm_programming_guide.pdf
See Page 266 ...
Here an short example how it should work (it calls the REST API from the HPSM to create a new incident:
var objConfig = {
"url" : "http://place:11400",
"path" : "/location/collaboration/notifications/register/",
"connect_timeout" : 30,
"read_timeout" : 30
};
var objPostData = {
"eId": "xxx111",
"deviceToken": "111111111111",
"deviceType": "iphone",
"applicationName": "huds"
};
createRecord( objPostData );
/**
* Create a new Incident with the RESTful API
*
* #param {Object} objRecord Object with all required fields
*
*/
function createRecord( objRecord ) {
var JSON = system.library.JSON.json();
var arrHeaders = [];
//Content Type application/json is required
//otherwise we will get an 501 error
var typeHeader = new Header();
typeHeader.name = "content-type";
typeHeader.value = "application/json";
var arrHeaders = new Array();
arrHeaders.push(typeHeader);
//build url for the request
//Default Action for POST is "create" so we don't need
//to add the action again
var cRequestUrl = objConfig.url+objConfig.path;
//convert the given object to an json string
cPostBody = system.library.JSON2.toJSON(objRecord);
try {
//lets run the the HTTP request
//HTTP Command - url to execute - http header - POST Body
var rcRequest = doHTTPRequest( "POST", cRequestUrl, arrHeaders, cPostBody, objConfig.connect_timeout, objConfig.read_timeout );
//convert response json string back to an object
var objResponse = JSON.parse(rcRequest);
print( objResponse.toSource() );
} catch( e ) {
//something goes wrong
//check also http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html
//to get the description of the given http response code like 401 etc.
//currently it's not possible (or i don't know how) to get the correct
//error response - for me it looks like that the HPSM has an filter
//which removes the response body if the response header is not 200
//if it's possible to use the reponse, we can use the same code
//as above JSON.parse() etc.
print("ERROR: \n"+e);
}
}
INFO1: Currently there is a limitation in the doHTTPRequest.
It can't handle the catch case correctly.
So even when there is an error, you will get the response as string.
And not the Object or whatever the response is.
INFO2: This example is based on my example to call the internal incident api.
I have modified it to your given data.
Code was created and tested successfully with HPSM 9.3+.
Hope this helps.
Greets
Marcus

Categories