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

Requesting JSON data from client through nodejs

本文关键字:JSON 数据 请求 客户端 nodejs 通过      更新时间:2023-09-26

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

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

如何在html中获取javascript来请求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

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

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

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

有人能用外行的话解释什么是JSONP吗?

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

因为您使用一个html源,另一个json源。这被视为跨域请求。

1-像callbackname({data: value})这样封装JSON对象。

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>