如何使用 Create-React-App 部署 Apollo Server?

How can one deploy Apollo Server with Create-React-App?

我正在尝试将我的应用程序部署到生产环境,但在将它们连接在一起时遇到了一些问题。

我的前端有一个 create-react-app,它由一个简单的 express/serve 服务器提供。在后端,我已经 NGINX 成功代理到我的 API 服务器,它使用 Apollo 来提供我的数据。 API 在端口 4000 上是 运行。

Apollo-Server 如下,运行正常:

import { resolve } from "path";
import dotenv from "dotenv";
const envi = process.env.NODE_ENV;
dotenv.config({ path: resolve(__dirname, `../.${envi}.env`) });

import "reflect-metadata";
import { connect } from "./mongodb/connect";
import { buildSchema } from "type-graphql";
import { ApolloServer } from "apollo-server";
import { SenateCommitteeResolver, HouseCommitteeResolver } from "./resolvers";
import { populateDatabase } from "./util";

(async () => {
  // Connect to MongoDB
  await connect();
  console.log(` Databases connected`);
  const schema = await buildSchema({
    resolvers: [HouseCommitteeResolver, SenateCommitteeResolver],
    emitSchemaFile: resolve(__dirname, "schema.gql"),
  });

  // If development, set database docs
  envi === "development" && (await populateDatabase());

  // Launch the server!
  const server = new ApolloServer({
    schema,
    playground: true,
  });

  // Server listens at URL
  const { url } = await server.listen(4000);
  console.log(` Server ready, at ${url}`);
})();

我正在尝试将我的快速服务器连接到 Apollo 服务器,但这正是我 运行 遇到问题的地方。该应用程序应该使用 Apollo 的客户端和 HTTP Link 进行连接,因为我也在前端使用 Apollo 客户端:

import React, { useEffect } from "react";
import { AppRouter } from "./routers";
import ReactGA from "react-ga";
import { ApolloProvider } from "@apollo/client";
import client from "./graphql/client";

import "./styles/index.scss";

function App(): React.ReactElement {    
  return (
    <ApolloProvider client={client}>
      <AppRouter />
    </ApolloProvider>
  );
}

export default App;

这是客户端文件:

import { ApolloClient, InMemoryCache, createHttpLink } from "@apollo/client";

const httpLink = createHttpLink({ uri: process.env.REACT_APP_API as string });
const cache = new InMemoryCache();

const client = new ApolloClient({
  link: httpLink,
  cache,
  connectToDevTools: true,
});

export default client;

但是,当用户导航到站点并且 站点本身 尝试向我的后端发出请求时,我收到了 CORS 错误:

Access to fetch at 'https://www.cloture.app/' from origin 'https://cloture.app' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

怎么了?如何在后端连接 Apollo 的客户端和我的 Apollo Server?

添加到这里,因为建议需要一些代码。

尝试添加:

const server = new ApolloServer({
    schema,
    playground: true,
    cors: {
      origin: "*" // it will allow any client to access the server, but you can add specific url also
    }

  });