You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js创建服务器路由时出现无效状态码RangeError问题求助

问题分析与修复方案

嘿,我来帮你排查下代码里的问题~你遇到的 RangeError: Invalid status code 是因为几个关键逻辑写错了,咱们一步步理清楚:

核心问题点

  • response.writeHead 参数完全误用:你在 renderHTML 里写了 response.writeHead(data),但 writeHead 第一个参数必须是HTTP状态码(比如200、404),而 data 是读取到的文件内容,把它传进去必然会触发状态码无效的错误。
  • 路由路径写错:case '.login' 多了个前置点,正确的路径应该是 case '/login',否则匹配不到登录页面的请求。
  • 错误处理不规范:读取文件失败时,你只返回了文本提示,没有设置对应的404状态码,不符合HTTP协议规范。
  • 默认路由缺少状态码:default分支里同样没有设置状态码,直接返回文本会导致请求响应不完整。

修复后的代码

app.js

var url = require('url')
var fs = require('fs')

function renderHTML(path, response) {
  fs.readFile(path, null, function(error, data) {
    if (error) {
      // 文件不存在时返回404状态码和提示
      response.writeHead(404, {'Content-Type': 'text/plain'})
      response.write('File not found')
    } else {
      // 读取成功返回200状态码和HTML内容
      response.writeHead(200, {'Content-Type': 'text/html'})
      response.write(data)
    }
    response.end()
  })
}

module.exports = {
  handleRequest: function(request, response) {
    var path = url.parse(request.url).pathname;
    switch(path) {
      case '/' : 
        renderHTML('./index.html', response)
        break;
      case '/login' :  // 修正路由路径,去掉前置点
        renderHTML('./login.html', response)
        break;
      default : 
        response.writeHead(404, {'Content-Type': 'text/plain'})
        response.write('Route not defined')
        response.end()
    }
  }
}

server.js(无需修改)

let http = require('http')
var app = require('./app.js')
http.createServer(app.handleRequest).listen(8001)

修复说明

现在你运行代码后:

  • 访问 http://localhost:8001/ 会正常加载根目录下的 index.html
  • 访问 http://localhost:8001/login 会加载 login.html
  • 文件不存在或路由不存在时,会返回标准的404状态码和对应提示,不会再触发状态码错误。

内容的提问来源于stack exchange,提问作者lohith kumar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:37:47