【问题标题】:React app failed to load resource: the server responded with a status of 404 GraphQLReact 应用程序加载资源失败:服务器响应状态为 404 GraphQL
【发布时间】:2021-03-28 21:36:36
【问题描述】:

我在我的服务器上部署了 react 应用程序,它在 localhost 上运行良好,但是当我尝试在我的服务器上使用它时,我得到了

加载资源失败:服务器响应状态为 404(未找到)shayankh.me/graphql

我在服务器上的根目录是 /var/www/html/

` 这是我的 server.js

  .connect(process.env.MONGO_URI, { autoIndex: false })
  .then(() => console.log("DB Connected"))
  .catch((err) => console.error(err));

// Initializes application
const app = express();

const corsOtions = {
  origin: "https://shayankh.me",
  Credential: true,
};
app.use(cors(corsOtions));

// Set up JWT authentication middleware
app.use(async (req, res, next) => {
  const token = req.headers["authorization"];
  if (token !== "null") {
    try {
      const currentUser = await jwt.verify(token, process.env.SECRET);
      req.currentUser = currentUser;
    } catch (err) {
      console.error(err);
    }
  }
  next();
});

//Create GraphiQL Application
app.use("/graphiql", graphiqlExpress({ endpointURL: "/graphql" }));

// Connect Schemas with  GraphQL
app.use(
  "./graphql",
  bodyParser.json(),
  graphqlExpress(({ currentUser }) => ({
    schema,
    context: {
      CarDetails,
      User,
      currentUser,
    },
  }))
);

app.use(express.static('public'));
express.static(path_join(__dirname, '../client/build'))
app.all('/', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  next();
 });

app.get('*', (req, res) => {
  res.sendFile(path.resolve(__dirname , "public", "index.html"))
});

const PORT = process.env.PORT || 5000;

app.listen(PORT, () => {
  console.log(`Server listening on PORT ${PORT}`);
});

和 index.js

  uri: "/graphql",
  fetchOptions: {
    credentials: "include",
  },
  request: (operation) => {
    const token = localStorage.getItem("token");
    operation.setContext({
      headers: {
        authorization: token,
      },
    });
  },
  onError: ({ networkError }) => {
    if (networkError) {
      console.log("Network Error", networkError);
    }
  },
});

const Root = ({ refetch, session }) => (
  <Router>
    <Fragment>
      <Navbar session={session} />
      <Switch>
        <Route path="/" exact component={App} />
        <Route path="/signin" render={() => <Signin refetch={refetch} />} />
        <Route path="/signup" render={() => <Signup refetch={refetch} />} />
        <Route
          path="/carDetail/add"
          render={() => <AddCar session={session} />}
        />
        <Route path="/carDetails/:_id" component={CarDetailPage} />
        <Route path="/profile" render={() => <Profile session={session} />} />
        <Redirect to="/" />
      </Switch>
    </Fragment>
  </Router>
);

const RootWithSession = withSession(Root);

ReactDOM.render(
  <ApolloProvider client={client}>
    <RootWithSession />
  </ApolloProvider>,
  document.getElementById("root")
);

我不知道我的问题是什么以及在哪里。 问题是否有可能因为服务器的根位置而导致我的应用程序无法找到 GraphQL? 我也在我的服务器上使用 nginx。

【问题讨论】:

  • 这两行是做什么的...? app.use(express.static('public')); 后跟 express.static(path_join(__dirname, '../client/build'))
  • 这两个呢...? app.use(cors(corsOtions)); 后跟 app.all('/', function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header(" Access-Control-Allow-Headers", "X-Requested-With"); next(); });
  • 这又如何......app.get('*', (req, res) => { res.sendFile(path.resolve(__dirname , "public", "index.html ")) });你应该如何处理 graphql 端点? 逐段调试您的代码,并尝试了解您的应用在服务器文件运行时会做什么
  • @rags2riches 那些行是为了在本地客户端上添加构建文件夹,我认为我使用 cors 来访问可以在后端和前端访问的 crosover 站点
  • 它们是否按您的意愿工作...?

标签: javascript reactjs graphql react-apollo graphql-js


【解决方案1】:

你有 .在api中,试试下面的代码

app.use(
  "/graphql",
  bodyParser.json(),
  graphqlExpress(({ currentUser }) => ({
    schema,
    context: {
      CarDetails,
      User,
      currentUser,
    },
  }))
);

【讨论】:

  • 你删除了 .来自“./graphql”?如果没有,请尝试删除它。
  • 不,它与 .没有 。任何我认为它与端口有关的东西,但不确定
猜你喜欢
  • 2016-11-01
  • 2018-01-29
  • 2020-07-04
  • 1970-01-01
  • 2019-07-04
  • 2021-11-20
  • 2018-02-26
相关资源
最近更新 更多