NodeJS中使用cookie-parser时网页无法加载,返回ERR_EMPTY_RESPONSE
Hey there! Let's break down why your page is throwing that ERR_EMPTY_RESPONSE when using cookie-parser, even though your logs show cookie values correctly. The most common culprit here is that your Express app isn't sending a response back to the client after processing the cookie—let's fix that.
Common Fixes to Try
1. You're Missing a Response in Your Route Handler
It sounds like you're successfully logging the cookie values, but if you don't explicitly send a response to the browser, it'll wait indefinitely and eventually throw an empty response error.
Wrong Example:
app.get('/', (req, res) => { console.log(req.cookies); // Logs work, but no response sent to client });
Corrected Example:
Add one of Express's response methods (like res.send(), res.render(), or res.json()) to send content back:
app.get('/', (req, res) => { console.log(req.cookies); res.send('Page loaded successfully!'); // Sends a response to the browser // Or use res.render('your-template') if you're using a view engine });
2. Check Middleware Order
Make sure cookie-parser is registered before your routes. If it's placed after your routes, the cookie data won't be parsed in time—but more importantly, ensure no other middleware is blocking the request from reaching your response-sending code.
Correct Middleware Order:
const express = require('express'); const cookieParser = require('cookie-parser'); const app = express(); // Register cookie-parser first app.use(cookieParser()); // Then define your routes app.get('/', (req, res) => { console.log(req.cookies); res.send('Hello from the server!'); }); app.listen(3000, () => console.log('Server running on port 3000'));
3. Verify No Other Middleware Is Blocking the Request
If you have other custom middleware (like logging or auth checks), make sure they're calling next() to pass the request along to the next middleware/route. Forgetting next() will leave the request hanging with no response.
Wrong Example:
app.use((req, res, next) => { console.log('Request received'); // Forgot to call next()—request gets stuck here }); app.use(cookieParser()); // Routes never run, no response sent
Corrected Example:
app.use((req, res, next) => { console.log('Request received'); next(); // Passes the request to the next middleware/route }); app.use(cookieParser()); // Routes run normally and send a response
Final Note
In almost all cases, this error happens because the browser never receives a response from your server. Double-check your route handlers to ensure you're sending content back, and verify your middleware chain is properly passing requests through. Once you add that missing response, your page should load while still letting you access cookie values via req.cookies.
内容的提问来源于stack exchange,提问作者Br0wn

