Nginx + GraphQL 连接被拒绝

ton*_*on1 4 nginx graphql next.js nginx-config

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

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

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

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

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

此 api 请求失败。

我不知道为什么,但是当我访问http://example.com:4000/graphql成功加载的 graphql 游乐场(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

}
Run Code Online (Sandbox Code Playgroud)

客户端应用程序的 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',
  })
}
Run Code Online (Sandbox Code Playgroud)

** 我尝试过...**

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

   location /graphql {
        proxy_pass http://localhost:4000/graphql;
   }
Run Code Online (Sandbox Code Playgroud)

我想我错过了 nginx conf 中的一些内容。我如何解决它?

ton*_*on1 11

我解决如下。

创建Apollo客户端

... createApolloClient(initialState, ctx) {
  return new ApolloClient({
    ...
    link: createHttpLink({ uri: '/graphql' })
Run Code Online (Sandbox Code Playgroud)

nginx

  location /graphql {
        proxy_pass http://localhost:4000/graphql;
   }
Run Code Online (Sandbox Code Playgroud)