2014-09-19 58 views
0

我在我的服务器上有一个文件(采用json格式)somefile.json,它定期更新选定的时间间隔。通过nodejs从客户端请求JSON数据

我有一个应用程序的NodeJS读取上request事件的文件在端口8080上监听并把它作为response

如何获取JavaScript在HTML的请求的JSON数据和日志它安慰? (尝试,但失败了,见下文)

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

我的应用程序的NodeJS

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使用我的本地机(OSX)上卷曲

{ 
    "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 
    } 
} 

给我的以下内容:

$ 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>  
+0

除去JSON.stringify – 2014-09-19 04:19:51

+0

哎@rnrneverdies控制台现在给出“意外的标记”,而不是登出JSON对象 – altimit 2014-09-19 05:13:48

+0

使用数据类型:JSONP跨域请求,这意味着请求到不同的域和数据类型:JSON为相同的域相同的原始请求。我建议使用dataType:'json' – 2014-09-19 05:19:58

回答

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>  
+0

Got it!因此,您在json字符串 “callbackname(”和“)”的前部和末尾附加的字符串可为您提供类似于 foo({id:value});在由ajitksharma提供的链接 http://stackoverflow.com/questions/3839966/can-anyone-explain-what-jsonp-is-in-layman-terms – altimit 2014-09-19 05:56:26

+0

yeap ............ 。 – 2014-09-19 06:00:37

2

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

这种讨论可能有助于理解JSONP:

Can anyone explain what JSONP is, in layman terms?

然而,一个替代方法是禁用谷歌Chrome浏览器的安全性,那么它会工作。但这不是一个解决方案。你需要使用JSONP格式。

相关问题