GraphQL-dotnet服务器无法与React应用连接,求助解决方案
Hey there! Let's work through getting your GraphQL-dotnet server connected with your React Apollo app. I've dealt with similar setup headaches before, so let's break this down step by step to get you up and running.
Before troubleshooting the React side, make sure your backend is actually responding to GraphQL requests correctly:
- Use GraphiQL (if you enabled it in your server) or Postman to send a test POST request to your server's GraphQL endpoint (e.g.,
https://localhost:5001/graphql). Include a simple query in the request body:query { # Replace this with a real field from your schema helloWorld } - If you get a valid JSON response back, your server is good to go. If not, fix backend issues first—common culprits are misconfigured endpoints or missing schema definitions.
- Don't forget CORS! React apps run on a different port (usually 3000) than your .NET server, so you need to allow cross-origin requests. Add this to your
Startup.csorProgram.cs:// In Program.cs (for .NET 6+) builder.Services.AddCors(options => { options.AddPolicy("AllowReactApp", policy => policy.WithOrigins("http://localhost:3000") // Your React app's URL .AllowAnyHeader() .AllowAnyMethod()); }); // Later in the middleware pipeline app.UseCors("AllowReactApp");
Let's make sure your React app is configured to talk to the server properly:
- First, install the required packages if you haven't already:
npm install @apollo/client graphql - Create an Apollo Client instance (I usually put this in
src/apollo/client.js):import { ApolloClient, InMemoryCache, createHttpLink } from '@apollo/client'; // Add this only if your server requires authentication (e.g., JWT) import { setContext } from '@apollo/client/link/context'; // Point this to your GraphQL-dotnet server's endpoint const httpLink = createHttpLink({ uri: 'https://localhost:5001/graphql', }); // Optional: Add auth header if your server needs it const authLink = setContext((_, { headers }) => { const token = localStorage.getItem('authToken'); return { headers: { ...headers, authorization: token ? `Bearer ${token}` : '', }, }; }); // Create the client—use authLink.concat(httpLink) if you added auth, else just httpLink const client = new ApolloClient({ link: authLink.concat(httpLink), cache: new InMemoryCache(), }); export default client; - Wrap your entire app with the
ApolloProviderin your root file (src/index.js):import React from 'react'; import ReactDOM from 'react-dom/client'; import { ApolloProvider } from '@apollo/client'; import client from './apollo/client'; import App from './App'; const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <ApolloProvider client={client}> <App /> </ApolloProvider> );
Now let's add a component to test if everything is working:
import { useQuery, gql } from '@apollo/client'; // Replace this query with one that matches your server's schema const GET_TEST_DATA = gql` query GetTestData { helloWorld } `; function TestGraphQLComponent() { const { loading, error, data } = useQuery(GET_TEST_DATA); if (loading) return <p>Loading data from server...</p>; if (error) return <p>Oops, error: {error.message}</p>; return <p>Success! Server says: {data.helloWorld}</p>; } export default TestGraphQLComponent;
Add this component to your App.js and run your React app to see if it pulls data correctly.
- Mismatched Endpoint: Double-check that the
uriin your Apollo Client matches your server's actual URL (port numbers, HTTP/HTTPS, and path all matter!). - CORS Errors: If your browser console yells about CORS, go back to step 1 and confirm your .NET CORS policy is allowing your React app's origin.
- Query Syntax Mistakes: GraphQL is case-sensitive! Make sure your query fields exactly match what's defined in your server's schema.
- Authentication Problems: If your server requires auth, ensure you're passing the correct token in the headers (check the browser's network tab to see if the authorization header is being sent).
If you're still stuck, share the error messages from your browser console and any relevant server logs—those will help pinpoint the exact issue!
内容的提问来源于stack exchange,提问作者Perumal.S

