在基于ExpressJS的Apollo Server中如何访问Request及底层应用Request对象?
Hey there! Let's tackle your two questions about working with request objects in an Express-based Apollo Server—they're closely linked, so I'll cover them side by side.
1. Core Method: Use Apollo's Context to Grab the Request Object
The standard (and recommended) way to access request data in Apollo Server is through the context object. When you set up your ApolloServer instance, you can define a context function that receives the underlying Express request (and response) as part of its arguments. You can then pass this request (or specific parts of it) to your resolvers for use in query/mutation logic.
Here's a full working example of setting this up:
const { ApolloServer } = require('apollo-server-express'); const express = require('express'); const app = express(); // Assume you've defined your schema and resolvers elsewhere const typeDefs = require('./typeDefs'); const resolvers = require('./resolvers'); const server = new ApolloServer({ typeDefs, resolvers, context: ({ req }) => { // `req` here is the native Express Request object // You can pass the full request to resolvers, or extract specific values for convenience return { expressRequest: req, // Example: Extract an authenticated user ID from request headers currentUserId: req.headers['x-auth-user-id'] }; }, }); // Start the server and mount it to your Express app await server.start(); server.applyMiddleware({ app }); app.listen(4000, () => { console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`); });
Then, in your resolvers, you can access the request object directly from the context parameter:
const resolvers = { Query: { getUserProfile: (parent, args, context) => { // Access the full Express request to read headers const userAgent = context.expressRequest.headers['user-agent']; console.log(`Request coming from: ${userAgent}`); // Use the pre-extracted user ID to fetch the user's profile return fetchUserProfile(context.currentUserId); }, }, };
2. Can You Access the Underlying Express Request Object? Absolutely!
When using Apollo Server with Express (via the applyMiddleware method), the req parameter in the context function is exactly the native Express Request object. That means you can use all the properties and methods you'd normally leverage in a standard Express route handler:
- Read request headers with
req.headers - Access cookies (if you've set up middleware like
cookie-parser) withreq.cookies - Get the client's IP address with
req.ip - Check the request HTTP method with
req.method - And any other native Express Request functionality you need!
For example, if you want to log the client's IP for every incoming request:
context: ({ req }) => { console.log(`Incoming request IP: ${req.ip}`); return { expressRequest: req }; }
Quick Side Note
If you were using Apollo Server's standalone mode (without integrating with Express), the request object in context would be an Apollo-specific wrapper. But since you're working with an Express-based setup, you're directly interacting with Express's native Request object—no extra layers or workarounds required.
内容的提问来源于stack exchange,提问作者Roman

