【问题标题】:Requesting JSON data from client through nodejs通过nodejs从客户端请求JSON数据
【发布时间】:2014-11-13 14:18:39
【问题描述】:

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

我有一个 nodeJS 应用程序,它在 request 事件上读取文件并在端口 8080 上侦听并将其作为 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);

一些文件.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>       

【问题讨论】:

  • 移除 JSON.stringify
  • 嘿@rnrneverdies 控制台现在提供“意外令牌”而不是注销 json 对象
  • 使用dataType:jsonp表示跨域请求,即对不同域的请求,dataType:json表示同域同源请求。我建议使用,dataType:'json'
  • 注意:我添加了一个错误 console.log(参见 html)还将 dataType 更改为 json 但是,这给出了:XMLHttpRequest cannot load http://127.0.0.1:8080/?_=1411105015186. No 'Access-Control-Allow-Origin'header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. 我尝试将以下内容添加到我的标题访问-Control-Allow-Origin':'*' in response.writeHead 但它仍然记录错误消息Uh Oh!
  • 是的,因为 html 不是从 127.0.0.1:8080 下载的,所以它考虑了跨域请求。然后,如果您从与 json 相同的服务器提供 HTML,则将起作用。但如果你不能这样做。返回 JSONP 并阅读 ajiksharma 给出的答案。

标签: javascript jquery html ajax node.js


【解决方案1】:

您可以对后端 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 格式。

【讨论】:

    【解决方案2】:

    当您使用 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>    
    

    【讨论】:

    • 知道了!因此,您在 json 字符串“callbackname(”和“)”的开头和结尾附加的字符串会为您提供类似于 foo({id:value}); 的内容。在 ajitksharma 的stackoverflow.com/questions/3839966/… 给出的链接中
    猜你喜欢
    • 2011-08-26
    • 1970-01-01
    • 1970-01-01
    • 2023-01-13
    • 2013-08-13
    • 1970-01-01
    • 2016-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多