Node.js / jQuery cross domain: ERR_CONNECTION_REFUSED

I am new to Node.js.

I am creating a simple node / express app that serves up a single web page containing a single 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 exchange rates. The JSON is then output to the developer console window.

The app works the first time the button is clicked, but subsequent clicks show the console window:

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

      

The Developer Tools Console Window Capture screen shows the result of the first click and then a second click when the connection fails.

enter image description here

The details of the error are 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 app looks like this:

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);
      

Run codeHide result


My html index page:

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

Run codeHide result


A free App ID is required to access openexchangerates.org data. Anyone who can help resolve this might have to go through their very short registration:

This link is here:

https://openexchangerates.org/signup/free

However, it is possible that my mistake is prominent for those with a better knowledge of node / Express / jQuery.

Thank you very much in advance

+3


source to share


2 answers


A method for determining your trees data

and json

leads to the failure of subsequent requests. Since you defined them in front, all requests will reuse them, meaning by the time you use JSON.parse data

for the second request, it data

will contain two valid json strings, thus making one invalid json string. To correct this, define data

and json

further into 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);

      

+3


source


The problem has to do with cross-generation request protection that happens on localhost with chrome. Try using a different browser, or just allow origin to all hosts (*) or your host ( http: // localhost: 3000 ):



app.use( express.static( __dirname + '/') );
app.use(function(req,res,next){
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');

    // intercept OPTIONS method
    if ('OPTIONS' == req.method) {
        res.send(200);
    }
    else {
        next();
    }
});

      

0


source







All Articles