通过nodejs从客户端请求JSON数据

时间:2014-09-19 04:13:23

标签: javascript jquery html ajax node.js

我的服务器上有一个文件(json格式)somefile.json,它会按照选定的时间间隔定期更新。

我是一个nodeJS应用程序,它在request事件中读取文件,并在端口8080上进行侦听并将其作为response发送出去

如何在html中获取javascript以请求json数据并将其记录在控制台中? (尝试但失败了,见下文)

(console.log的原因是让我知道它已成功加载。)

我的nodeJS app

var http = require('http'), 
    fs   = require('fs'),
    filename = "somefile.json"; 

var server = http.createServer();
server.on('request', function(request, response) { 
    response.writeHead(200, {'Content-Type': 'application/json'})
    fs.readFile(filename, "utf8", function (err, data) {
                if (err) throw err;
                response.write(JSON.stringify(data));
                response.end();
                });
    });

    server.listen(8080);

somefile.json

{
    "message": {
        "success":"Information inserted successfully.",        "update":"Information updated successfully.",
        "delete":"Information deleted successfully.",
    },
    "Jennifer": {
        "status":"Active"
    },    "James": {
        "status":"Active",
        "age":56,        "count":10,
        "progress":0.0029857,
        "bad":0
    }
}

在我的本地机器(OSX)上使用cURL给了我以下内容:

$ curl -i -H "Accept: application/json" http://127.0.0.1:8080
HTTP/1.1 200 OK
Content-Type: application/json
Date: Fri, 19 Sep 2014 03:39:41 GMT
Connection: keep-aliveTransfer-Encoding: chunked

"{\n    \"message\": {\n        \"success\":\"Information inserted successfully.\",\n        \"update\":\"Information updated successfully.\",\n        \"delete\":\"Information deleted successfully.\",\n    },\n    \"Jennifer\": {\n        \"status\":\"Active\"\n    },\n    \"James\": {\n        \"status\":\"Active\",\n        \"age\":56,\n        \"count\":10,\n        \"progress\":0.0029857,\n        \"bad\":0\n    }\n}\n"

我的HTML(不工作)

<html>                                                                                                                                                                                                                                                                          
<head></head>                                                                                                                                                                                                                                                                   
<body>                                                                                                                                                                                                                                                                          
<script src="jquery-2.1.1.min.js"></script>                                                                                                                                                                                                                                     
<script>                                                                                                                                                                                                                                                                        
$(function() {                                                                                                                                                                                                                                                                  
    $.ajax({                                                                                                                                                                                                                                                                
        url: 'http://127.0.0.1:8080',                                                                                                                                                                                                                                       
            contentType:"jsonp",                                                                                                                                                                                                                                            
            dataType: 'jsonp',                                                                                                                                                                                                                                              
            cache: false,                                                                                                                                                                                                                                                   
            success: function() { console.log('Success!'); },                                                                                                                                                                                                               
            error: function() { console.log('Uh Oh!'); }     
            });                                                                                                                                                                                                                                                                 
});                                                                                                                                                                                                                                                                             
    </script>                                                                                                                                                                                                                                                                   
</body>                                                                                                                                                                                                                                                                         
</html>       

2 个答案:

答案 0 :(得分:2)

你可以对后端API进行AJAX调用,它需要返回JSONP格式而不仅仅是JSON,否则你会得到错误。这是由于相同的原产地政策:
https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy

此讨论可能有助于理解JSONP:

Can anyone explain what JSONP is, in layman terms?

但是,另一种方法是禁用Google Chrome浏览器的安全性,然后它就能正常运行。但这不是解决方案。您需要使用JSONP格式。

答案 1 :(得分:1)

当您使用html的一个源代码和json的另一个源代码时。这被视为跨域请求。

1 - 将您的JSON对象包含在此callbackname({data: value})

var http = require('http'), 
    fs   = require('fs'),
    filename = "somefile.json"; 

var server = http.createServer();
server.on('request', function(request, response) { 
    response.writeHead(200, {'Content-Type': 'application/json'})
    fs.readFile(filename, "utf8", function (err, data) {
                if (err) throw err;
                response.write("callbackname(");
                response.write(data);
                response.write(")");
                response.end();
                });
    });

    server.listen(8080);

2 - 将jsonpCallback: "callbackname"添加到您的ajax请求中。

<html>                                                                                                                                                                                                                                                                          
<head></head>                                                                                                                                                                                                                                                                   
<body>                                                                                                                                                                                                                                                                          
<script src="jquery-2.1.1.min.js"></script>                                                                                                                                                                                                                                     
<script>                                                                                                                                                                                                                                                                        
$(function() {                            

    $.ajax({                                                                                                                                                                                                                                                                
        url: 'http://127.0.0.1:8080',    
            jsonpCallback: "callbackname",
            contentType: "application/json",                                                                                                                                                                                                                                   
            dataType: 'jsonp',                                                                                                                                                                                                                                              
            cache: false,                                                                                                                                                                                                                                                   
            success: function(json){                                                                                                                                                                                                                                        
            console.log(json);                                                                                                                                                                                                                                         
}                                                                                                                                                                                                                                                                               
            });                                                                                                                                                                                                                                                                 
});                                                                                                                                                                                                                                                                             
    </script>                                                                                                                                                                                                                                                                   
</body>                                                                                                                                                                                                                                                                         
</html>