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

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!

Related

Calling an internal API from within Express

I have a simple API route set up in Express (consumed mainly via my Angular frontend):
app.post('/api/sendEmail', emailApi.sendEmail);
I've made a module that sits in my backend and also needs to call this service. I figured the easiest way was to do a POST request:
request({
url: '/api/sendEmail',
method: 'POST',
json: {
template: template.toLowerCase(),
obj: mailObj
}
}, function(error, response, body){
console.log('error', error);
console.log('response', response);
console.log('body', body);
});
However, I get this error:
Error: Invalid URI "/api/sendEmail"
What am I doing wrong here?
Change Url to'http://127.0.0.1:3000/api/sendEmail', because you're
calling an internal api with in express or you can also use localhost
in place of 127.0.0.1.
request({
url: 'http://127.0.0.1:3000/api/sendEmail', //on 3000 put your port no.
method: 'POST',
json: {
template: template.toLowerCase(),
obj: mailObj
}
}, function (error, response, body) {
console.log({error: error, response: response, body: body});
});
emailApi.sendEmail is just a function. You are much better off calling it directly. Using the network in this manner would be a serious waste of resources.
On a practical note, there are some complex issues about how to address yourself on the network. Usually you can accomplish this via localhost, but there's no guarantee that the server is listening at that address. So you'll have to take that into account.
You need to use an absolute URI (including the protocol, domain, and port if it's not listening on the default port).
For example, if you know that the server will be listening at localhost:3000, you would want to replace your url value with 'http://localhost:3000/api/sendEmail'.
Assuming you are not using a web server like nginx and are developing on localhost. The express app does not know from where the request has originated. Try setting your Url as http://localhost:300/api/sendEmail.

Angular app $http request to node app on localhost

I'm running a nodejs app on localhost:3000. I have a front-end tutorial angular page that calls localhost like this...
$scope.msg = 'requesting';
$http({
method: 'GET',
url: 'http://localhost:3000/'
}).then(function(response) {
$scope.msg = response;
}, function(response) {
$scope.msg = 'err ' + JSON.stringify(response);
});
I can see from the console on my node app that it is answering with 200 and a json object {foo:'bar'}. But the $scope.msg variable ends up looking like this...
err {
"data":null,
"status":-1,
"config":{
"method":"GET",
"transformRequest":[
null
],
"transformResponse":[
null
],
"url":"http://localhost:3000/",
"headers":{
"Accept":"application/json, text/plain, */*"
}
},
"statusText":""
}
Why would the client think there's a problem when the server produced a good response? Running the request in the browser works fine.
Loading the angular page (http://localhost:9000) the browser dev tools, I see this...
But for some reason, the response tab is empty. When I make the same request (http://localhost:3000/) with the browser and watch, I see the JSON in the response tab.
As SLaks mentioned in the comment, it happens because of the Same-Origin Policy. Your node app is running on localhost:3000, while your client is on localhost:9000.
You'll need to set Access-Control-Allow-Origin header on server side to allow requests coming from localhost:9000.
Make sure your server reply with a correct content type header:
Content-Type:application/json; charset=utf-8

Cannot get proper json response from my simple nodejs server

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!!!!

HTTP Request Redirection in angular and node/express

Suppose that I have following angular http request which redirects to a route in the server side (node/express) to perform another http request to web api.
Based on the following code:
Would the angular http request will ever have errorCallback? If yes, under what situation?
What is a possible condition for the if(error) to produce an error in the server side http request? Is it client side http error? Any other else?
Should the http request in server side have error as true, will the app crash?
Angular http request:
$http({
method: 'GET',
url: 'webServerUrl'
}).then(function successCallback(response) {
alert('success');
}, function errorCallback(response) {
alert('fail');
});
Server side http request
var request = require('request');
exports.getSearchResults = function (req, res) {
request({
method: 'POST',
url: 'apiUrl'
}
, function (error, response, body) {
if (error) {
res.jsonp('Unknown error. Please try again later');
}
else {
res.jsonp(body);
}
}
)}
Would the angular http request will ever have errorCallback? If yes, under what situation?
Yes. If the request to the server times out or fails, it will be called.
What is a possible condition for the if(error) to produce an error in the server side http request? Is it client side http error? Any other else?
No, it will only cause an error if the call to the api fails.
Should the http request in server side have error as true, will the app crash?
No, it shouldn't. The error object is an object, not a boolean.
By the way, you should know that it is not standard practice to issue a GET request in the client and then issue a POST request to your api. A POST request implies some sort of state change, whereas a GET should not. Either make them all GET, if the calls can be made repeatedly without any side effects, or make them all POST.

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/

Categories

Resources