Cannot get proper json response from my simple nodejs server - javascript

SERVER : cloud server, Ubuntu 15.04 x64. nginx is installed listening port 80.
SERVER program : written using NodeJS, simply response in json. like { msg : "done" }
Client (HTML page using React and JQuery) : simple ask the server for the json data.
The problem is on client
// 1)
this.serverRequest = $.get({url:'https://api.github.com/users/octocat/gists', success:function(ret) {
// 2)
//this.serverRequest = $.get({url:'http://my_server_ip_address:7534/test', success:function(ret) {
alert("ok done");
}.bind(this), error:function(e) {
alert("Error : " + e);
}.bind(this)});
I have no problem with 1) request. I do receive some data.
but with 2) request, 'error' function is called and executing 'alert('Error :' + e);' only shows 'Error : [object Object]'. It does not show any useful information..
So I thought my nodejs server program has some problems and I went on searching for answers. I think I try all possible answers..
1) setting iptable to accept port 7534.
2) making nodejs server to listen on 0.0.0.0
3) using res.json().. res.jsonp()
I can see {msg : "done"} if I try with Chrome. so I guess my nodejs server works.

Look the message of error. Instead of alert(e) use console.log(e), for see properties of object e.

ok following #Juven_v 's answer..I figured the 'object' was Error object. And I was able to see the error message through console.log(e).
Here is summary of the solution I found:
1) When the server program responses, put header **Access-Control-Allow-Origin with value *.
I am using nodeJS with express so the code is
res.header('Access-Control-Allow-Origin', '*');
And the client requests with the url.
I use JQuery and the code is
$.get({
url: "http://address!!!!",
type: "GET",
success: function(result) {
console.log("yay");
console.log(result);
},
error: function (err) {
console.log(err);
},
});
If the above client code does not work, then try to add 'dataType: "json"'
2) If I add the following code in the server program..
res.header('Access-Control-Allow-Headers', 'Content-type');
then the client request must have
//contentType: "application/json",
References :
How does Access-Control-Allow-Origin header work?
jQuery AJAX to node server throws net::ERR_CONNECTION_REFUSED
net::ERR_CONNECTION_REFUSED Error jQuery ajax node.js
THANK YOU ALL!!!!

Related

My restify POST error data isn't visible in the client JavaScript

I'm trying to implement a POST REST call in node.js using restify. In this instance, I want to send an error to the browser. Unfortunately, I haven't figured out how to send the error data so that the browser JavaScript can see the error data I sent.
When I call the doPost() function on the browser, it performs an ajax POST call to my server. The server code returns with an error 400 and a small JSON object containing an error message.
The browser then goes to the .fail() function. However, the textStatus is "error", errorThrown is an empty string, and the jqXHR properties are readyState : 0, responseText : "", status : 0, statusText : "error".
What can I do to get my error data from Node to the client browser?
Here is the jQuery code that runs in the browser:
function doPost() {
$.ajax({
url: "http://localhost:3979/api/address",
type: "POST",
// Request body.
data: {key: "mykey", address: "myaddress"}
})
.done(function(data) {
// Show the formatted JSON in the text area.
$("#outputTextArea").val(JSON.stringify(data, null, 2));
})
.fail(function(jqXHR, textStatus, errorThrown) {
// An error occurred. Display the error information.
$("#outputTextArea").val(
"status: " + jqXHR.status +
", textStatus: " + textStatus +
", errorThrown" + errorThrown + "\r\n");
});
}
And here is the Node.js code that runs on the server:
const restify = require('restify');
// Create the server.
let server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3979, function () {
console.log(`${server.name} listening to ${server.url}`);
});
// POST call that returns an error.
server.post("/api/address", async (req, res) => {
res.send(400, {errorMessage: "The value given does not appear to be valid."});
});
Edit: Both res.status(422); res.send("The value given does not appear to be valid."); and res.send(new BadRequestError('meh')); fail in the exact same way. The jqXHR properties are the same (zero for readyState and status, empty string for responseText), textStatus is "error, and errorThrown is an empty string.
I tested my .ajax code against a known working POST call, and it gets proper values, including a JSON responseText.
Can someone please try this out in node.js and show me what I'm doing wrong, or show me the right way to send an error to the browser. So far, nothing works.
Edit: After further tests and experiments, this time with curl, I found that my POST call works and returns expected values.
I used this curl command to retrieve the status code:
curl -s -o /dev/null -w "%{http_code}" -X POST http://localhost:3979/api/address
And received this response: 400
I then used this curl command:
curl -X POST http://localhost:3979/api/address
And received this response:
{"errorMessage":"The value given does not appear to be valid."}
So it appears that the problem exists on the browser end.
This stackoverflow question seems to indicate a cross domain problem (page: www.mydomain.com/register, REST: server.mydomain.com/rest). However, I am doing all of this using localhost, so I don't see how the browser could see a cross domain issue here.
Any ideas on how to get REST POST errors to show up in the browser when running on localhost?

Jquery AJAX always errors

I am using nginx web server and running a website on localhost. I want to be able to get my files through the server with jquery's AJAX function but it always throws an error. I've made a folder called TESTFOLDER inside my 'data' folder and it has a txt file called test.txt.
This is my javascript code
$.ajax({
url: "../data/TESTFOLDER/",
type: 'GET',
dataType: "txt",
headers: {
Accept : "text/html",
"Content-Type": "text/html"
},
success: function(data){
console.log('there was a success');
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('there was an error');
}
});
This is my nginx configuration block for the folder
location /data/TESTFOLDER/ {
autoindex on;
try_files $uri $uri;
add_header Content-Type application/txt;
}
I always get this error:
NetworkError: 500 Internal Server Error
when it tries to reach the data/TESTFOLDER
I have of course tried it simpler than this, without the headers and all that. Nothing seems to work though. Please help if you can.
EDIT:
Yes, I can get to the file by typing out local host/data/TESTFOLDER/test.txt in my browser.
The ../ doesn't seem to be causing problems because in both cases, I get the error message 500 Internal Server Error - local host/data/TESTFOLDER/, i.e. not local host/../data/TESTFOLDER/
The server error log says: 2020#2644: rewrite or internal redirection cycle while internally redirecting to "/data/TESTFOLDER/", client: 127.0.0.1, server: localhost, request: "GET /data/TESTFOLDER/ HTTP/1.1", host: "localhost", referrer: "http:// localhost/index.html"
NOTE: The word local host is in two seperate words here because they won't allow me to post links.
EDIT2: I should note that while local host/data/TESTFOLDER/test.txt works fine in my browser, local host/data/TESTFOLDER/ throws the error 500. Should this be happening?
your url is malformed. if you want to use a relative path in an Ajax call, you don't need to use the ...
source: Relative URLs in AJAX requests
You can just use url: "/data/TESTFOLDER/". Your current url tries to access http://localhost:63542/../Data/TESTFOLDER/, which probably doesn't exist, but the server tries to locate it and throws an error.
You can catch different http-statuscodes with ajax.
Example:
$.ajax({
statusCode: {
500: function() {
// do something
}
}
});
You misuse try_files and get internal redirection loop.
Also, MIME type for text is text/plain.

XMLHttpRequest cannot load http://localhost:8089/jquery. Origin null is not allowed by Access-Control-Allow-Origin

I am trying to hit a webservice from jquery(ajax) using chrome. But when i try to invoke webservice i am getting below error and it is not even reaching the server
Error :XMLHttpRequest cannot load http://tomohamm-t420:8089/jquery. Origin null is not allowed by Access-Control-Allow-Origin.
Below is a sample ajax call which i am using:
//Build W/S-Request query as String object..
var id = '123';
var query = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sch="http://www.tibco.com/schemas/jQuerySample/jquery/Schema.xsd"';
query += '<soapenv:Header/';
query += '<soapenv:Body';
query += '<sch:EmpDetailsRequest';
query += '<sch:empID' + id + '</sch:empID';
query += '</sch:EmpDetailsRequest';
query += '</soapenv:Body';
query += '</soapenv:Envelope';
// set end point url..
var endpointUrl = 'http://tomohamm-t420:8089/jquery';
//ajax call to W/S..
$.ajax({
url : endpointUrl,
type : "POST",
beforeSend : function(xhr) {
xhr.setRequestHeader("SOAPAction", "/GetEmpByID");
},
data : query,
dataType : "xml",
contentType : "text/xml; charset=\"utf-8\"",
complete : function(xmldata,stat,response) {
console.log("W/S-Response: "+xmldata.responseText);
},
success : function(data) {
console.log('W/S Successful!');
},
error : function(textStatus, errorThrown) {
console.log('W/S Failed!');
console.log('Error Status :: ' +textStatus);
console.log('Error Message :: ' +errorThrown);
}
});
I found a way to avoid this issue. That is i have to open chrome using the below command:
cd C:\Program Files (x86)\Google\Chrome\Application
Chrome.exe --disable-web-security
But this cannot be done on every machine which tries to open my application.
So is there anyway to include this setting inside jquery application so that i can directly open chrome and run it?
I guess you are making ajax calls from a local file, right? If you want to do this some server side coding are needed.
Try this in you server side where you process the ajax request and send the response, adding the Access-Control-Allow-Origin header to the HTTP response and set the value to *. Here's a piece of Java code for your information.
response.setHeader("Access-Control-Allow-Origin", "*")
No. If you don't control the endpoint, your best bet is to proxy the request through your own server, and add the appropriate Access-Control-Allow-Origin headers.

Dojo XHR don't send a request to other server at all, but everything works in jQuery

I have the development enviroment consisting of the Apache HTTP server for fast Javascript development and the application server (WebSphere) that provides the JSON REST API. Of course, Access-Control-Allow-Origin is set (to *).
The following code results in error:
xhr.post({
url: "http://localhost:8080/rest-sample/rest/test/list",
handleAs: "json",
load: onload
});
RequestError: Unable to load
http://localhost:8080/rest-sample/rest/test/list status: 0
ErrorCtor()create.js (Zeile 13) onError()xhr.js (Zeile 80)
var err = Error.call(this, message),
There is a JavaScript error thrown instead of sending the AJAX request. However, in the same time, the following jQuery snipplet function perfect:
var url = "http://localhost:8080/rest-sample/rest/test/list"
$.post(url, {}, onLoad, 'json')
My question is: what I'm doing wrong? How to send the AJAX request to the other server using Dojo?
I'm using dojo 1.9
Your server must also send Access-Control-Allow-Headers: x-requested-with.
I think xhr.post is no longer supported, i suggest to use dojo/request, or at least dojo/request/xhr
require(["dojo/request/xhr"], function(xhr){
xhr("http://localhost/rest-sample/rest/test/list", {
handleAs: "json",
method: "POST"
}).then(function(data){
// Do something with the handled data
}, function(err){
// Handle the error condition
}, function(evt){
// Handle a progress event from the request if the
// browser supports XHR2
});
});
If it's Cross origin problem i would suggest using ReverseProxy on your http server.
add this to your httpd.conf
ProxyPass /rest-sample/ http://localhost:8080/rest-sample/

Ajax call to a local Phantom.js server from local js script

I have set up an Apache server running locally that hosts my web application (written in ExtJs). I have also a secon local server made with phantom.js and listening on port 8080 :
var server, service;
server = require('webserver').create();
service = server.listen(8080, function (request, response) {
response.statusCode = 200;
response.write('<html><body>Hello!</body></html>');
response.close();
});
Now I'd like to do an Ajax request from my application to the phantom server :
Ext.Ajax.request({
url: 'http://localhost:8080',
method: 'GET',
success: function(response){
console.log('RESPONSE: ', response);
},
filure: function(response){
console.log('failure: ', response);
}
});
But when running this script I'm getting :
"NetworkError: 400 Bad Request - http://localhost:8080/?_dc=1336648497292" in the console. Does this operation violate the same origin policy ? Or is it something else ? Going to localhost:8080 shows the proper response, so the server is running properly.
your html is also on localhost:8080? If not (different port => different host) then you have the cross domain ajax problem.
Ajax doesn't work on File protocals!! It only works on HTTP or HTTP . I have found a course on udemy,mentors says ajax wont works on file:d://(path) protocals. So he shifted his files to web server and then he explained his topic on ajax.
hope this helps!

Categories

Resources