使用createServer创建的服务器无响应问题排查求助
问题分析与修正
核心问题点
createServer回调传入错误:创建服务器时,你把functionListener当成了回调参数的占位符,而非传入预先定义好的请求处理函数,导致实际没有任何逻辑处理请求。- 响应对象属性误用:
res.headersSent和res.statusCode是属性而非方法,不能加()调用,否则会触发TypeError,直接中断请求处理流程。 - 条件判断逻辑漏洞:两个独立的
if语句会导致,即使第一个条件匹配并执行了res.end(),第二个条件仍会被判断,尝试重复发送响应头和内容,抛出Error: Can't set headers after they are sent.错误。 Content-Type不匹配:你设置Content-Type: text/plain,但返回的是HTML和JSON内容,会导致浏览器解析异常,无法正常渲染预期内容。- 缺失必要依赖与变量:代码未引入
http模块,也未定义port变量,服务器根本无法正常启动。
修正后的代码
// 引入http模块 const http = require('http'); // 定义端口变量 const port = 3000; const options = { keepAlive: true, } const functionListener = (req, res) => { // 正确访问属性,而非调用方法 console.log("headerSent:", res.headersSent); console.log("statusCode :", res.statusCode); if (req.url === '/') { // 返回HTML时设置正确的Content-Type res.writeHead(200, "succeeded", { 'Content-Type': 'text/html' }); res.write('<html><body><p>This is default Page.</p></body></html>'); res.end(); } // 使用else if避免重复判断和响应 else if (req.url === '/hello') { res.writeHead(200, "succeeded", { 'Content-Type': 'text/html' }); res.write('<html><body><p>This is hello Page.</p></body></html>'); res.end(); } // 处理未匹配的路由 else { res.writeHead(404, { 'Content-Type': 'text/plain' }); res.end('404 Not Found'); } } // 正确传入请求处理函数 const server = http.createServer(options, functionListener); server.listen(port, () => { console.log(`Server running at http://localhost:${port}/`); });
额外说明
如果需要返回JSON格式响应,需调整Content-Type为application/json,示例如下:
if (req.url === '/') { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ data: 'default!' })); }
内容的提问来源于stack exchange,提问作者Amrmsmb
相关产品推荐
相关产品推荐

