Adding headers to c# HTTP server - javascript

I'm trying to make a HTTP server (listener) in c# using the "Simple HTTP server in c#" - (http://www.codeproject.com/Articles/137979/Simple-HTTP-Server-in-C), and send requests to it using javascript.
This is what the code looks like:
The HandleRequest function in c#:
public override void handleGETRequest(HttpProcessor p)
{
p.httpHeaders.Add("Access-Control-Allow-Origin", "*");
if (p.http_url.Equals("/test"))
{
p.outputStream.Write("Test accomplished");
Console.Log("Server responded to TEST request successfully");
return;
}
if (p.http_url.StartsWith("/goto"))
{
string[] args = p.http_url.Split('/');
//x - [2]
//y - [3]
//z - [4]
//f - [5]
myPrinter.SendCommand(string.Format("G1X{0}Y{1}F10000", args[2], args[3]));
p.outputStream.Write("response succeeded");
Console.Log("goto command was executed");
}
if (p.http_url.StartsWith("/commandlist"))
{
string[] args = p.http_url.Split('/');
//[2] - commands
string[] commands = args[2].Split('$');
for (int i = 0; i < commands.Length; i++)
{
myPrinter.commands.Add(commands[i]);
}
//myPrinter.HandleCommandList();
p.outputStream.Write("response succeeded");
Console.Log("goto command was executed");
}
if (p.http_url.StartsWith("/execute"))
{
p.outputStream.Write("Executing " + myPrinter.commands.Count + " commands\n");
myPrinter.HandleCommandList();
}
}
The request sending in JS look like that:
function sendGCODE() {
var xmlhttp = new XMLHttpRequest();
var url = "http://localhost:1300/commandlist/" + document.getElementById("Text1").value;
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myArr = xmlhttp.responseText;
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
alert('Response received');
document.getElementById("resultP").innerHTML = arr;
}
}
But when I try sending the request from the JS code, it just tells me that "Access-Control-Allow-Origin" header is missing, and so it can't send the request. I added that header in the beginning of the handleGETRequest() function like that:
public override void handleGETRequest(HttpProcessor p)
{
p.httpHeaders.Add("Access-Control-Allow-Origin", "*");
So why doesn't it work? The serverside software doesn't throw an error, but the JS code is still upset because of the missing header.
What am I doing wrong? Thanks! (the rest of the server side code is in the link above)

I think you should enable CORS for your server to accept those requests, take a look at this guide , maybe it will help.

Related

AJAX call is failing, is the url path correct?

I am a beginner in web development (self learner),and I am trying to connect my javascript .js file to java servlet through AJAX where I am stuck. It's not making the AJAX call, or not entering the java code, returning to the call back function. Is my url mapping or path specified correct? Or can you see some other error? Thanks!
JS code:
a = parseInt(document.getElementById("num"+ 0).value);
var xhr = new XMLHttpRequest();
xhr.open("GET", "/add?num1=" + a , true ); // true is for Asynchronous request
alert("here3 a=" + a);
xhr.send();
var ret = eval(xhr.responseText); //just trial
alert("eval" + ret);
xhr.onreadystatechange = () => {
if(xhr.readyState == 4 && xhr.status == 200){
document.getElementbyId('ajaxResponse').innerHTML = xhr.responseText;
var ret = eval(xhr.responseText);
alert("Callback1 = " + ret);
}
else(alert("Callback failed"))
};
Java servlet:
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
System.out.println("Add Servlet called");
int i = Integer.parseInt(req.getParameter("num1"));
// int j = Integer.parseInt(req.getParameter("num2"));
// int k = i+j;
PrintWriter out = res.getWriter();
out.println("Result is i=" + i);
res.setContentType("text/plain");
res.getWriter().write(i);
}
Web.xml
(servlet): callJava
com.AddServlet
(servlet-mapping):callJava
/add
It just goes in else condition of callback function ("Callback failed"). Also, does the location/folder structure of the servlet or js file matters, if mapping is done in .xml file? Thanks!
I can't really help you with the server side part as I'm not familiar with the framework that you are using. But the following are my recommendations for the client side code:
Use let instead of var;
true flag to make request async is not necessary because it is the default and will be soon deprecated.
It is preferable to use the new addEventListener API instead of directly adding the handler to the intended target.
Fully setup your request before calling open and send.
Use === operator instead of ==.
const a = parseInt(document.getElementById("num" + 0).value);
let xhr = new XMLHttpRequest();
xhr.addEventListener('readystatechange', (e) => {
if(e.target.readyState === 4){
document.getElementbyId('ajaxResponse').innerHTML = e.target.responseText;
}
});
xhr.open("GET", "/add?num1=" + a);
xhr.send();
Please let me know if it works. If it does, you may want to check if your server is correctly setting the "found" response code (200).
Ok I figured it out, the url should just be "add?num1=" instead of "/add?num1=". It does map through .xml file! Now I am reaching java file and status is 200 :D
Next I am trying to figure out how to return back value any ajax response value from java servlet to javascript file or html file. Should I do it somehow in xhr.onreadystatechange() function? It's still not satisfying both conditions [if(xhr.readyState == 4 && xhr.status == 200)]. Any suggestions?

Trying to post to a .txt file fails but performing a get does work

My partner and I are trying to get a domain that I own, communicate with a ios app that is run on objective c to work via http. He is using the code that was provided by this link Sending an HTTP POST request on iOS.
He is able to do a GET to receive the data in my .txt page but when he performs a PUT to try and write to that file so that I can get that data it fails. We are both rather new to http so it is possible that we are missing something. A concern we have is that he doesn't have the privileges to write to this file. Any advice would help, thanks!
Here is the javascript I am using on my side. I added a header to my response to try and resolve the cors issue.
(function () {
window.onload = function () {
httpGetAsync("http://students.washington.edu/bharatis/distances.txt", processData)
//alert("hello inside onload");
document.getElementById("first").innerHTML = leader1;
document.getElementById("second").innerHTML = leader1;
document.getElementById("third").innerHTML = leader1;
//window.onbeforeunload = update;
}
function processData(responseText) {
//alert(responseText);
var txt = "";
var x = responseText.getElementsByTagName('Distance'); // Talk to alex about
for(i = 0; i < x.length; i++) {
txt += x[i].childNodes[0].nodeValue;
}
var result = parseDouble(txt);
alert(result);
}
function httpGetAsync(theUrl, callback) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.setRequestHeader("Access-Control-Allow-Origin", "*");
xmlHttp.send("response message");
}
})();

How can I pass a parameter from javascript to RESTful web service using XMLHttpRequest

When i try to print the received parameter at the web service.
The parameter is empty.
If I view domain server log of glass fish server I can see the following
print:
Inside getJson()
countryKey =
So I understand the request arruved to the web service, but the parameter
that was sent from the javascript url is empty
// This is the code of the web service method
#GET
#Produces(MediaType.APPLICATION_JSON)
public String getJson(String countryKey) {
System.out.println("Inside getJson()");
System.out.println("countryKey = " + countryKey);
return "countryKey = " + countryKey;
}
// This is the javascript method
function populateDistrictList() {
var element = document.getElementById("selectCountry");
var selectedCountryKey = element.value;
var selectedCountry = element.options[element.selectedIndex].text;
var xmlHttp = new XMLHttpRequest();
var url = "http://localhost:8080/MissionWS/webresources/generic?selectedCountryKey="+selectedCountryKey;
xmlHttp.open('GET', url, true);
xmlHttp.responseType = 'json';
if (xmlHttp) {
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
alert(xmlHttp.responseText);
} else {
alert("Something is wrong !");
}
}
};
xmlHttp.send();
}
}
Please try adding the #QueryParam to your method signature as follows.
public String getJson(#QueryParam("selectedCountryKey") String countryKey)

Login using Javascript and REST

I made a REST service, which will return a String "hej" if the log in is true.
I have tested in Java with a rest client and it works fine, but pretty new to javascript and need some help.
I'm using this function
function UserAction() {
console.log(User());
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "http://localhost:8080/Footballmanagerrestservice/webresources/login");
xhttp.setRequestHeader("login", User());
xhttp.responseType = 'text';
xhttp.onreadystatechange = function () {
console.log('DONE', xhttp.readyState);
if (xhttp.readyState == 4) {;
// handle response
var response = xhttp.responseText;
console.log(response);
if (response == "hej") {
var url = "http://localhost:8080/FM3/spil2.jsp";
window.location.href = url;
}
}
};
// send the request *after* the callback is defined
xhttp.send();
return false;
}
function User() {
username = document.getElementById("username").toString();
username = document.getElementById("password").toString();
var UserAndPass = "?username=" + username + "&password=" + password;
return UserAndPass;
}
I show you the client i have i Java, maybe you can see why it's not working.
public static void main(String[] args) {
Client client = ClientBuilder.newClient();
String root="http://localhost:8080/Footballmanagerrestservice/webresources/";
String functionPath="login";
String parameters="?username=s153518&password=holger";
Response res = client.target(root+functionPath+parameters)
.request(MediaType.APPLICATION_JSON).get();
String svar = res.readEntity(String.class);
System.out.println(svar);
}
first part of the code looks ok, the following instead must be handled inside a function because is intrinsically asynchronous
var response = JSON.parse(xhttp.responseText);
console.log(response);
if (response.toString() == "hej") {
var url = "http://localhost:8080/FM3/spil2.jsp";
window.location.href = url
}
return false;
doc: https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest/onreadystatechange
essentially you're trying to handle the response as a syncrhonous call, but it's not, the response it's not immediatly avaiable, for this reason you have to register a callback (from the doc must be attached to the field onreadystatechange) that will be triggered by javascript as soon as the server response is available.
try to change it like so:
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4) {
// handle response
var response = JSON.parse(xhttp.responseText);
console.log(response);
if (response.toString() == "hej") {
var url = "http://localhost:8080/FM3/spil2.jsp";
window.location.href = url
}
}
}
xhr.send();

Load ~ 400 (Bad Request). XmlHttpRequest works on local, but not on server-side

I am working on async load (using XMLHttpRequest .readystate & .responseText) of product table contents on pagination or filter changing. Funtions I wrote work perfectly but on local only. On apache/ngnix server-side it returns bad request. Please help.
function loadContent(link) {
var http = createRequestObject();
if( http ) {
http.open('load', link);
http.onreadystatechange = function () {
if(http.readyState == 4) {
var div = document.createElement('div');
div.innerHTML = http.responseText;
var all = div.getElementsByTagName('div');
for (var i = 0, len = all.length; i < len; i++) {
if (all[i] && all[i].getAttribute('id') == 'to-ajax') {
var deep = all[i].getElementsByClassName('product-layout col-lg-4');
$('.load').before(deep);
}
}
}
}
http.send(null);
} else {
document.location = link;
}
}
function createRequestObject() {
try { return new XMLHttpRequest() }
catch(e) {
try { return new ActiveXObject('Msxml2.XMLHTTP') }
catch(e) {
try { return new ActiveXObject('Microsoft.XMLHTTP') }
catch(e) { return null; }
}
}
}
Error warning refers to this line of code ~ } http.send(null);
It seems that problem is on .onreadystatechange function, but have no idea how to test it to define what an exact issue is.
The first argument to open needs to be a string containing an HTTP request method. "load" is not an HTTP request method. Examples include "GET" and "POST". The invalid HTTP is likely causing your server to respond with the Bad Request error.

Categories

Resources