简体   繁体   中英

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.

在此输入图像描述

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

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

Issue comes from Cross origin requests protection which happens on localhost with chrome. Try to use other 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();
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM