gpt4 book ai didi

javascript - 通过nodejs向客户端请求JSON数据

转载 作者:行者123 更新时间:2023-11-28 19:35:46 25 4
gpt4 key购买 nike

我的服务器上有一个文件(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);

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

Can anyone explain what JSONP is, in layman terms?

但是,一种替代方法是禁用 Google Chrome 浏览器的安全性,然后它就可以工作。但这不是解决方案。您需要使用 JSONP 格式。

关于javascript - 通过nodejs向客户端请求JSON数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25926257/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com