【发布时间】:2019-06-10 12:03:33
【问题描述】:
当对 NodeJS 服务器(不是本地主机)进行 ajax 调用时,它不会返回任何内容。在进行 ajax 调用时,NodeJS 在我的 NodeJS 控制台 (ssh) 中显示结果。 NodeJS 在 ajax 调用后 10-15 秒崩溃并出现错误。
我尝试过使用 Pool 但我不明白。
前端
"use strict";
var btn = document.getElementById('button');
function ajax(){
let req = new XMLHttpRequest();
req.onreadystatechange = function(){
if( this.readyState === 4 && this.status === 200){
let data = JSON.parse( this.responseText );
console.log(data);
}
};
req.open("GET", "/ajax/", true);
req.send();
};
btn.addEventListener("click", (e)=>{
e.preventDefault();
ajax();
});
后端(nodejs)
const {Client} = require('pg');
const db = new Client({
user: "x",
password: "x",
host: "x",
port: 123,
database: "abc",
ssl: true
});
module.exports = {
async select( sql ){
try{
await db.connect();
console.log("Connected to DB");
const result = await db.query( sql );
console.table(result.rows); // <-- Shows the data i want to send back.
return JSON.stringify(result.rows);
}
catch(ex){
console.log("We messed up! " + ex);
}
finally{
await db.end();
console.log("DB connection closed");
}
}
};
我希望 ajax 调用从 postgres 数据库返回数据。我在 nodeJS 控制台中看到的相同数据。
Error: Client has already been connected. You cannot reuse a client.
events.js:177
throw er; // Unhandled 'error' event
^
Error: This socket has been ended by the other party
at TLSSocket.writeAfterFIN [as write] (net.js:407:14)
at Connection.end
code: 'EPIPE'
【问题讨论】:
标签: javascript node.js asynchronous node-postgres