Javascript 无法使用pg promise和vue.js从postgres获取数据
我想将pg_promise与feathersjs和vuejs结合使用,以显示在postgres db上运行的查询结果,我的sql.js如下所示 sql.jsJavascript 无法使用pg promise和vue.js从postgres获取数据,javascript,postgresql,vue.js,feathersjs,pg-promise,Javascript,Postgresql,Vue.js,Feathersjs,Pg Promise,我想将pg_promise与feathersjs和vuejs结合使用,以显示在postgres db上运行的查询结果,我的sql.js如下所示 sql.js const express = require('express'); const jsonexport = require('jsonexport'); const dbgeo = require('dbgeo'); const router = express.Router(); function dbGeoParse(data) {
const express = require('express');
const jsonexport = require('jsonexport');
const dbgeo = require('dbgeo');
const router = express.Router();
function dbGeoParse(data) {
return new Promise((resolve, reject) => {
dbgeo.parse(
data,
{
outputFormat: 'geojson',
},
(err, result) => {
if (err) {
reject(err);
} else {
resolve(result);
}
},
);
});
}
// expose sql endpoint, grab query as URL parameter and send it to the database
router.get('/sql', (req, res) => {
const { app } = req;
const sql = req.query.q;
const format = req.query.format || 'topojson';
console.log(`Executing SQL: ${sql}`, format); // eslint-disable-line
// query using pg-promise
app.db
.any(sql)
.then((data) => {
console.log('data',data)
// use dbgeo to convert WKB from PostGIS into topojson
return dbGeoParse(data).then((geojson) => {
res.setHeader('Content-disposition', 'attachment; filename=query.geojson');
res.setHeader('Content-Type', 'application/json');
return geojson;
});
})
.then((data) => {
res.send(data);
})
.catch((err) => {
// send the error message if the query didn't work
const msg = err.message || err;
console.log('ERROR:', msg); // eslint-disable-line
res.send({
error: msg,
});
});
});
module.exports = router;
我已经将我的app.js配置为使用sql.js作为路由,方法是添加以下行
const pgp = require('pg-promise')({
query(e) {
console.log(e.query); // eslint-disable-line
},
});
const connectionString = 'postgres://abc:abc123@localhost:5678/gisdb';
// initialize database connection
const app = express(feathers());
app.db = pgp(connectionString);
app.use('/sql', require('sql'));
但当我从vue组件调用如下所示的handleSubmit函数时
handleSubmit() {
const SQL = "select * from spatial_search(searchmethod := 'id',sale_price :=10000,tax_ogcid :=
84678,distance := 0.5)";
const queryType = 'sql';
fetch(`/${queryType}?q=${encodeURIComponent(SQL)}`)
.then(res => {console.log('res',res.json())})}
我得到以下错误
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
Uncaught(在promise中)语法错误:JSON中位置0处出现意外标记<
我想我可能做错了什么。有人能帮我吗?服务器很可能正在发送HTML(这种错误的常见原因,
res.text()).then(console.log)
以准确输出返回主应用程序html的响应,但我希望它从postgis db返回json,你能告诉我怎么做吗?你需要调试你的服务器代码-或者可能有更熟悉它的人会昏迷过来-我对你的服务器代码了解不够,无法帮助你调试。你正在pg promise中记录查询方法,但你的问题不包括它的输出。确实应该;)