簡體   English   中英

node.js / jQuery跨域:ERR_CONNECTION_REFUSED

[英]node.js / jQuery cross domain: ERR_CONNECTION_REFUSED

我是Node.js的新手。

我正在創建一個簡單的節點/快速應用程序,它為一個包含一個按鈕的網頁提供服務,當點擊該按鈕時,它會向Express路由發出jQuery ajax請求。

對於包含外匯匯率的一些json數據,路由回調向openexchangerates.org發出http.get請求。 然后將JSON輸出到Developer Tools控制台窗口。

該應用程序適用於第一次按鈕單擊,但在隨后的任何單擊時,控制台窗口將顯示:

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

Developer Tools控制台窗口的屏幕抓取顯示第一次單擊的結果,然后在拒絕連接時顯示第二次單擊。

在此輸入圖像描述

錯誤詳情如下:

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

我的簡單Node / Express應用程序如下:

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

我的html索引頁是:

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

對於openexchangerates.org來提供數據,需要一個免費的應用程序ID。 任何能夠幫助解決此問題的人都可能需要通過他們的簡短注冊:

那個鏈接在這里:

https://openexchangerates.org/signup/free

然而,對於那些具有更好的Node / Express / jQuery知識的人來說,我的錯誤可能是非常明顯的。

提前謝謝了

您定義datajson變量的方式導致后續請求失敗。 由於您預先定義了它們,所有請求都將重用它們,這意味着當您為第二個請求提供JSON.parse datadata將包含兩個有效的json字符串,從而產生一個無效的json字符串。 要解決此問題,請在回調中進一步定義datajson

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

問題來自於使用chrome在localhost上發生的跨源請求保護。 嘗試使用其他瀏覽器或只允許來自所有主機(*)或主機( 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();
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM