【问题标题】:Nginx won't serve the json responsesNginx 不会提供 json 响应
【发布时间】:2018-11-10 12:24:33
【问题描述】:

我有一个在服务器上正确运行的单页应用程序,跨不同的 url 提供页面:

  • example.com
  • example.com/jsonendpoint

但是当我尝试访问一个旨在返回 JSON 的端点时,我得到了一个 HTML 响应。 nginx 配置如下所示:

server {
    root /home/myapplication/server/public;

  location / {
    proxy_pass http://myapplication/;
    proxy_redirect off;
    try_files $uri $uri/ /index.html;
  }

  location /jsonendpoint {
    proxy_pass http://myapplication/;
    default_type application/json;
    proxy_redirect off;
  }
}

如果我注释掉 try_files 行,那么 JSON 响应可以正常工作,我仍然可以访问 example.com 的根 URL,但是当我尝试访问 example.com/jsonendpoint 时,nginx 返回 404。

如何修复配置以使两者都能正常工作?

编辑

当我从它所在的 VPS 中 curl 服务器时:

curl -i -H "Accept: application/json" http://localhost:3000/jsonendpoint

我收到 JSON 响应:

Content-Type: application/json; charset=utf-8

当我从本地机器发出相同的 curl 请求时(这意味着通过 nginx,那么响应类型是错误的:

Content-Type: text/html; charset=UTF-8

这排除了问题出在后端服务器的可能性。

mime.types 文件确实添加了 json mime 类型,并且它被 nginx 包含。我也尝试过强制每个位置块的响应类型(参见上面的 sn-p)。

【问题讨论】:

    标签: nginx


    【解决方案1】:

    检查您的mime types 中是否有类似的内容:

    application/json      json;
    

    然后尝试使用以下方式查询您的网站:

    curl -i -H "Accept: application/json" http://your-site
    

    如果您的应用程序返回 json,请检查标头 content-type,它应该是:

    content-type: application/json
    

    如果你得到类似的东西:

    content-type: text/html; charset=utf-8
    

    检查您的后端以添加正确的内容类型。

    如果你想强制类型,试试这个:

    location / {
        default_type application/json;
        # ...
    }
    

    【讨论】:

    • 没有。我已经用一些额外的细节更新了这个问题
    • @Simpleton 你传递的 proxy_pass url 的输出“内容类型”是什么?
    猜你喜欢
    • 1970-01-01
    • 2019-07-17
    • 1970-01-01
    • 2019-06-27
    • 2014-10-22
    • 1970-01-01
    • 1970-01-01
    • 2020-08-10
    • 1970-01-01
    相关资源
    最近更新 更多