【发布时间】: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':'*' inresponse.writeHead但它仍然记录错误消息Uh Oh! -
是的,因为 html 不是从 127.0.0.1:8080 下载的,所以它考虑了跨域请求。然后,如果您从与 json 相同的服务器提供 HTML,则将起作用。但如果你不能这样做。返回 JSONP 并阅读 ajiksharma 给出的答案。
标签: javascript jquery html ajax node.js