Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js / jQuery cross domain: ERR_CONNECTION_REFUSED

I'm new to Node.js.

I'm creating a simple node/express application that serves a single web page containing one button that when clicked makes a jQuery ajax request to an Express route.

The route callback makes an http.get request to openexchangerates.org for some json data containing foreign exchange rates. The JSON is then output to the Developer Tools console window.

The application works on the first button click, but on any subsequent clicks the console window displays:

GET http://127.0.0.1:3000/getFx net::ERR_CONNECTION_REFUSED

A screen grab of the Developer Tools console window shows the result of the first click, and then the second click when the connection is refused.

enter image description here

The error detail is as follows:

GET http://127.0.0.1:3000/getFx net::ERR_CONNECTION_REFUSED    jquery-2.1.3.min.js:4
n.ajaxTransport.k.cors.a.crossDomain.send    jquery-2.1.3.min.js:4   
n.extend.ajax           (index):18
(anonymous function)    jquery-2.1.3.min.js:3
n.event.dispatch        jquery-2.1.3.min.js:3
n.event.add.r.handle

My simple Node/Express application is as follows:

var express = require('express');
var app = express();
var http = require("http");
var data = "";
var json;

console.log( "__dirname", __dirname );
app.use( express.static( __dirname + '/') );

var options = {
  host:"openexchangerates.org",
  path:"/api/latest.json?app_id=<get free ID from openexchangerates.org>"
};

app.get("/", function( req, res ) {
  res.sendFile('index.html', { root: __dirname });
})

app.get("/getfx", function(req, res) {
  console.log("Route: getFx");
  getFx(res);
})

function getFx(res) {
  console.log("http getFx");
  http.get(options, function (response) {
    response.on("data", function (chunk) {
      //console.log("data:\n"+chunk);
      data += chunk;
    });
    response.on("end", function () {
      json = JSON.parse(data);
      console.log("http response end:");
      res.end( data );
    });
    response.on("error", function (e) {
      console.log("error:\n" + e.message);
    });
  })
}

app.listen(3000);

My html index page is:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Get FX</title>
    <script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
    <script>
        $(document).ready(function() {
            console.log( "document ready");
           $("#btnFx").click(function() {
                console.log('clicked', this );
                $.ajax({
                    url : "http://127.0.0.1:3000/getFx",
                    dataType : "json",
                    success : function(json) {
                        console.log("json returned:\n", json);
                    }
                });
            } );
        })
    </script>

</head>
<body>
    <button id="btnFx" style="width:200px">Get foreign exchange rates</button>
</body>

For openexchangerates.org to serve the data, a free app id is required. Anyone able to help resolve this may have to go through their very short sign up:

That link is here:

https://openexchangerates.org/signup/free

However it's possible that my mistake is glowingly obvious to those with better Node/Express/jQuery knowledge.

Many thanks in advance

like image 600
user2190690 Avatar asked May 17 '26 16:05

user2190690


1 Answers

The way you defined your data and json vars is causing subsequent requests to fail. Since you defined them up front, all requests will re-use them, meaning by the time you JSON.parse data for the second request, data will contain two valid json strings, thus making one invalid json string. To fix this, define data and json farther down in the callback.

var express = require('express');
var app = express();
var http = require("http");
//var data = "";
//var json;

console.log( "__dirname", __dirname );
app.use( express.static( __dirname + '/') );

var options = {
  host:"openexchangerates.org",
  path:"/api/latest.json?app_id=<get free ID from openexchangerates.org>"
};

app.get("/", function( req, res ) {
  res.sendFile('index.html', { root: __dirname });
})

app.get("/getfx", function(req, res) {
  console.log("Route: getFx");
  getFx(res);
})

function getFx(res) {
  console.log("http getFx");
  http.get(options, function (response) {
    var data = "";
    var json;
    response.on("data", function (chunk) {
      //console.log("data:\n"+chunk);
      data += chunk;
    });
    response.on("end", function () {
      console.log("http response end:");
      json = JSON.parse(data);
      res.json(json);
    });
    response.on("error", function (e) {
      console.log("error:\n" + e.message);
    });
  })
}

app.listen(3000);
like image 138
Kevin B Avatar answered May 19 '26 06:05

Kevin B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!