Nginx + GraphQL 连接被拒绝

Nginx + GraphQL Connection Refused

  1. 我的客户端 (next.js) 应用 运行 在端口 3000

  2. 我的服务器 (graphql) 应用 运行 在端口 4000

我的网站是https://example.com,nginx会通过代理端口3000。

如果用户访问网站,则页面加载成功。

但在幕后,在我的网页中,一些 api 请求被发送到 graphql 服务器。 (http://localhost:4000)

本api次请求失败。

我不知道为什么,但是当我访问 http://example.com:4000/graphql 时,graphql playground (graphiql?) 加载成功,我可以发送一些查询并且结果显示良好。但是网页请求失败

nginx/sites-enabled/example.com

server {
        listen 80;
        listen [::]:80;
        server_name www.example.com example.com;
        return 301 https://example.com$request_uri;
}


server {
    listen 80;
    listen [::]:80;
    server_name example.com;


    location / {
        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }

    listen [::]:443 ssl ipv6only=on; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}

客户端应用程序的 graphql 部分

export default function createApolloClient(initialState, ctx) {
  return new ApolloClient({
    ssrMode: Boolean(ctx),
    link: authLink.concat(new HttpLink({
      uri: 'http://localhost:4000/graphql', // Server URL (must be absolute)
      credentials: 'same-origin', // Additional fetch() options like `credentials` or `headers`
      fetch,
    })),
    cache: new InMemoryCache({ fragmentMatcher }).restore(initialState),
    credentials: 'include',
  })
}

** 我试过的...**

我将以下代码片段添加到 nginx conf(上面的 listen [::]443 部分)并重新启动 nginx 服务,但没有任何改变。

   location /graphql {
        proxy_pass http://localhost:4000/graphql;
   }

我想我在 nginx conf 中遗漏了一些东西。我该如何解决?

我解决如下。

创建ApolloClient

... createApolloClient(initialState, ctx) {
  return new ApolloClient({
    ...
    link: createHttpLink({ uri: '/graphql' })

nginx

  location /graphql {
        proxy_pass http://localhost:4000/graphql;
   }