2016-12-25 64 views
0

我已經有很多時間瞭解爲什麼我的Node.js服務使用郵遞員工作得非常好。如果你看下面你可以看到我的node.js服務工作正常。但jQuery代碼(調用GetAllNotifyTypesFunc();)如何在沒有回調的jquery ajax請求內使用Node.js?

給我的錯誤:(如何調用正確的郵遞員都和jQuery不回調?)

enter image description here

的Node.js:


'use strict'; 
var express = require("express"); 
var app = express(); 
var MongoClient = require('mongodb').MongoClient; 
var router = express.Router(); 

app.get('/Notifies', function (req, res) { 
    MongoClient.connect('mongodb://127.0.0.1:27017/Test', function (err, db) { 
     if (err) throw err; 
     var coll = db.collection('Notifies'); 
     coll.find({}).toArray(function (err, result) { 
      if (err) { 
       res.send(err); 
      } else { 

       // res.writeHead(200, { 
       // 'Content-Type': 'application/json' 
       // }); 
       // res.end('callback(\'' + JSON.stringify(result) + '\')'); 
       res.writeHead(200, { 
        'Content-Type': 'application/json' 
       }); 
       res.end(JSON.stringify(result)); 
       // res.json(result); 
      } 
     }) 
    }) 
}); 

var port = Number(process.env.PORT || 5000); 
app.listen(port, function() { 
    console.log("Listening on " + port); 
}) 

如果我使用郵遞員:

enter image description here

$(function() { 

    GetAllNotifyTypesFunc(); 

}); 

var GetAllNotifyTypesFunc = function() { 
    console.log("notify"); 

    $.ajax({ 
     url: 'http://127.0.0.1:5000/Notifies', 
     dataType: "jsonp", 
     async: false, 
     //jsonpCallback: "callback", 
     cache: false, 
     timeout: 5000, 
     success: function (data) { 
      console.log(data); 
      console.log(JSON.parse(data)); 
     }, 
     error: function (jqXHR, textStatus, errorThrown) { 
      alert('error ' + textStatus + " " + errorThrown); 
     } 
    }); 


} 

回答

1

你說jQuery的響應將是jsonp,但它是json。你需要檢查的區別,我想你應該使用:

dataType: "json", 

JSONP是FO可執行的功能,請參閱(What are the differences between JSON and JSONP?

+0

什麼跨域?沒有jsonp,我可以處理跨域? – Penguen

+0

jquery-2.0.3.min.js:6 XMLHttpRequest無法加載http://127.0.0.1:5000/Notifies?_=1482684143180。請求的資源上沒有「Access-Control-Allow-Origin」標題。原因'http://127.0.0.1:13227'因此不被允許訪問。 send @ jquery-2.0.3.min.js:6 Test.html:36錯誤錯誤NetworkError:未能在'XMLHttpRequest'上執行'發送':未能加載'http://127.0.0.1:5000/Notifies ?_ = 1482684143180' 。 – Penguen

+1

@Penguen - 你知道瀏覽器中的跨站安全限制嗎?除非該網站明確啓用交叉來源請求,否則您不能從當前網頁域以外的網站請求Ajax呼叫。您可以搜索「node.js CORS」以瞭解如何在您的node.js服務器中啓用交叉源請求。郵差不像瀏覽器那樣限制交叉源請求。 – jfriend00