【发布时间】:2021-09-20 13:31:50
【问题描述】:
我正在学习 React。我有一个 React 应用程序,它使用 google api 允许登录用户搜索书籍并将其保存到 Mongo 数据库。在开发中一切正常,但是当我为生产运行构建时,我收到一个 404 错误,即找不到请求路径。
我的服务器端 server.js:
const express = require('express');
const { ApolloServer } = require('apollo-server-express');
const path = require('path');
const db = require('./config/connection');
const { typeDefs, resolvers } = require('./schemas');
const { authMiddleware } = require('./utils/auth');
const app = express();
const PORT = process.env.PORT || 3001;
const server = new ApolloServer({
typeDefs,
resolvers,
context: authMiddleware
});
server.applyMiddleware({ app });
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
// if we're in production, serve client/build as static assets
if (process.env.NODE_ENV === 'production') {
app.use(express.static(path.join(__dirname, '../client/build')));
}
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, '../client/build/index.html'));
});
db.once('open', () => {
app.listen(PORT, () => {
console.log(`API server running on port ${PORT}!`);
console.log(`Use GraphQL at http://localhost:${PORT}${server.graphqlPath}`);
});
});
我的客户端 App.js:
import React from 'react';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import SearchBooks from './pages/SearchBooks';
import SavedBooks from './pages/SavedBooks';
import Navbar from './components/Navbar';
import {
ApolloClient,
InMemoryCache,
ApolloProvider,
HttpLink,
ApolloLink,
from
} from "@apollo/client";
import { onError } from '@apollo/client/link/error';
const httpLink = new HttpLink({
uri: '/graphql'
});
const errorLink = onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors)
graphQLErrors.forEach(({ message, locations, path }) =>
console.log(
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,
),
);
if (networkError) console.log(`[Network error]: ${networkError}`);
});
const tokenLink = new ApolloLink((operation, forward) => {
const token = localStorage.getItem('id_token');
operation.setContext({
headers: {
authorization: token ? `Bearer ${token}` : 'No token found in App.js'
}
});
return forward(operation);
});
const client = new ApolloClient({
// The `from` function combines an array of individual links
// into a link chain
link: from([errorLink, tokenLink, httpLink]),
cache: new InMemoryCache()
});
function App() {
return (
<ApolloProvider client={client}>
<Router>
<>
<Navbar />
<Switch>
<Route exact path='/' component={SearchBooks} />
<Route exact path='/saved' component={SavedBooks} />
<Route render={() => <h1 className='display-2'>Wrong page!</h1>} />
</Switch>
</>
</Router>
</ApolloProvider>
);
}
export default App;
这是我第一次提出问题,所以如果需要其他信息/有帮助,请告诉我,我会编辑问题。谢谢。
【问题讨论】:
标签: reactjs react-router apollo-client react-apollo apollo-server