2013-09-21 67 views
2

在我的节点js文件,我有这样的代码:获取协议

var jqxhr = $.getJSON("favs.json", function() { 
    console.log("success"); 
}) 
.done(function() { 
    console.log("second success"); 
}) 
.fail(function(jqxhr, textStatus, error) { 
    var err = textStatus + ", " + error; 
    console.log("Request Failed: " + err); 
}) 
.always(function() { 
    console.log("complete"); 
}); 

而在服务器有一个在同一个目录中称为favs.json文件上面的js文件。但是,当我访问该页面时,出现错误:

Request Failed: error, Protocol not supported. 

有谁知道最新错了吗?

谢谢。

+0

在服务器上我们读取文件不是getJSON getJSON用于前端 – Gaurav

回答

1

And in the server there is a file called favs.json in the same directory as the above js file.

如果文件位于服务器上,为什么不用fs.readFile()来阅读?

var fs = require('fs'); 
var fileContents; 
fs.readFile('./favs.json', function (err, data) { 
    if (err) throw err; 
    fileContents = data; 
    // ... 
}); 

如果你真的想使用XMLHttpRequest该文件的内容,

  1. 确保它是通过HTTP(S)服务器在您的应用程序访问。
  2. 输入完整的URL,你想获取的文件(例如:http://localhost/favs.json

显然$.getJSON使用一个意外的(可能为null)值作为该协议没有规定当它。