我对 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/