gpt4 book ai didi

javascript - Node.js express |尝试获取 JSON 时始终为 null

转载 作者:搜寻专家 更新时间:2023-11-01 00:45:30 25 4
gpt4 key购买 nike

我是 node.js 的新手,我想在 HTML5 网站上接收来自 PostgreSQL 数据库的 JSON。因此,在服务器端,我使用 node-postgres 模块进行数据库连接,还使用 ​​express 模块进行通信。 PostgreSQL 查询返回一个 JSON 对象。

服务器端:

var express = require('express');
var app = express();

app.get('/data', function(req, res){
var pg = require('pg');

var conString = "postgres://postgres:postgres2@localhost/spots";

var client = new pg.Client(conString);
client.connect(function(err) {
if(err) {
res.send('could not connect to postgres');
}
client.query('SELECT * from spots_json where id=3276', function(err, result) {
if(err) {
res.send('error running query');
}
res.send(JSON.stringify(result.rows[0].json));
client.end();
});
});
});

app.listen(3000);

客户端:

<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js" ></script>

<script>

$.get('http://localhost:3000/data',{}, function(data){
alert(JSON.parse(data));
},"json");

</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>

如果我在浏览器上导航到 http://localhost:3000/data,我会得到:

{\"type\":\"Point\",\"coordinates\":[-2.994783,43.389217]}

所以我看到服务器正在正确发送字符串化的 JSON,但在客户端我总是收到空数据。我一定是有什么误解。

最佳答案

好的,这就是我的代码到目前为止的样子,对于任何可以提供帮助的人:

服务器端

var express = require('express');
var app = express();

app.get('/data', function(req, res){
var pg = require('pg');

var conString = "postgres://postgres:postgres2@localhost/spots";

var client = new pg.Client(conString);
client.connect(function(err) {
if(err) {
res.send('could not connect to postgres');
}
client.query('SELECT * from spots_json where id=3276', function(err, result) {
if(err) {
res.send('error running query');
}
res.set("Content-Type", 'text/javascript'); // i added this to avoid the "Resource interpreted as Script but transferred with MIME type text/html" message
res.send(JSON.stringify(result.rows[0].json));
client.end();
});
});

});

app.listen(3000);

客户端

<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"></meta>
<meta charset="utf-8"></meta>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js" ></script>

<script>

$.get('http://localhost:3000/data?callback=?',{}, function(data){
alert(data.type);
},"json");

</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>

客户端现在在http://localhost:8888/prueba/prueba.html上执行

我得到一个带有以下响应的 js:

"{\"类型\":\"点\",\"坐标\":[-2.994783,43.389217]}"

响应可以在下面的截图中看到:

https://www.dropbox.com/s/zi4c5pqnbctf548/pantallazo.png

但现在警报甚至没有显示...

我想我需要一些光照。

关于javascript - Node.js express |尝试获取 JSON 时始终为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19821965/

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