【问题标题】:nginx + PostgreSQL: return JSON objectnginx + PostgreSQL:返回 JSON 对象
【发布时间】:2019-03-21 08:23:56
【问题描述】:

我喜欢运行 PostgreSQL 10 服务器作为后端,使用 ngx_postgres 作为前端的 nginx。数据库以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;
    }
}

但结果以文本形式返回,带有转义的双引号,而不是预期的 JSON:

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

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

【问题讨论】:

    标签: json postgresql nginx jsonb


    【解决方案1】:

    你可以试试 c2h5oh 框架。它是一个使用 Nginx 和 PostgresSQL 的强大功能构建 Web 应用程序的快速轻量级框架

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

    【讨论】:

      【解决方案2】:

      经过几次尝试,我能够通过更改 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。

      【讨论】:

        猜你喜欢
        • 2021-06-30
        • 1970-01-01
        • 1970-01-01
        • 2018-09-30
        • 2015-01-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多