听起来您想创建一个 HTTP 端点,对吗?
为此,您可能需要使用express.js。
有很多关于使用 express 创建 HTTP 服务器的很棒的教程,但是这会让你开始:
通过节点包管理器安装 express 模块。
从您的终端/命令行中,键入:
cd project-name
npm install express --save
将您的节点服务器修改为以下内容:
var Massive = require("massive")
, http = require("http") // import http
, express = require("express") // import express
, app = express(); // instantiate your app
/* database config */
var connectionString = "postgres://postgres:postgres@localhost/postgres";
var db = Massive.connectSync({connectionString : connectionString});
/* http routes */
app.get("/",function(req,res){
// req is the request object
// res is the response object
db.query("Select * from company", function (err, data) {
// send a http response with status code 200 and the body as the query data.
res.status(200).send(data);
});
});
/* listen in port 3000 */
var server = http.createServer(app);
server.listen(3000);
此应用程序将侦听端口 3000,并响应对 '/' 的请求,例如http://localhost:3000/。将查询数据库并将结果作为对 HTTP 请求的响应发送。