nginx + PostgreSQL: return JSON 对象

nginx + PostgreSQL: return JSON object

我喜欢 运行 PostgreSQL 10 服务器作为后端,nginx ngx_postgres 作为前端。数据库以JSONB格式存储数据:

=# CREATE TABLE dump (
   id   bigserial primary key,
   data jsonb     not null
);

数据可以这样查询:

=# SELECT data FROM dump;

使用ngx_postgres,可以直接从nginx访问PostgreSQL数据库:

upstream postgresql {
    postgres_server localhost dbname=default user=user password=secret;
}

server {
    listen 80;

    location /postgresql/ {
        rds_json          on;

        postgres_pass     postgresql;
        postgres_query    HEAD GET "SELECT data FROM dump"
        postgres_rewrite  no_rows 410;
        postgres_output   rds;
    }
}

但结果是 return 编辑为文本,带有转义双引号,而不是预期的 JSON:

[{"data":"{\"id\": \"00ce160e5cbb49b9bc2ee6f243f87841\", \"name\": \"foo\"}"}] 

如何 return 将查询结果作为 JSON 对象?

你可以试试c2h5oh框架。它是一个使用 Nginx 和 PostgresSQL

的强大功能构建 Web 应用程序的快速轻量级框架

https://github.com/genosse/c2h5oh/

经过几次尝试,我能够通过更改 nginx 配置输出 JSON。必须安装并加载 nginx 模块 headers-more 才能工作:

server {
    listen 80;

    location /postgresql/ {
        rds_json          off;

        postgres_pass     postgresql;
        postgres_query    HEAD GET "SELECT json_agg(data) FROM dump"
        postgres_rewrite  no_rows 410;
        postgres_output   text;
        more_set_headers  'content-type: application/json';
    }
}

首先,必须将 PostgreSQL 输出格式设置为 text。然后,必须使用 more_set_headers 覆盖默认内容类型。 nginx 提供的结果有效 JSON.