lohith kumar
lohith kumar

Reputation: 55

_http_server.js:190 throw new RangeError(`Invalid status code: ${originalStatusCode}`); in node js?

i'm new to nodeJS technology, Actually i want to create a server and provide routing to another two files based on request.url but i runs , it was showing the above error, where it is showing invalid status code,

Here is my code

app.js

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

function renderHTML(path , response){
   fs.readFile(path,null, function(error , data){
       if(error){

           response.write('file not found')
       } else{
           response.writeHead(data)
       }
       response.end()
   })   
}
module.exports = {
    handleRequest : function(request , response){
        response.writeHead(200, {'Content-Type' : 'text/html'})
        var path = url.parse(request.url).pathname;
        switch(path) {
            case '/' :
               renderHTML('./index.html', response)
               break;
            case '.login' : 
               renderHTML('./login.html', response)
               break;
            default : 

               response.write('route not defined')
               response.end()
        }
    }
}

And my server.js looks like

    let http = require('http')
var app = require('./app.js')

http.createServer(app.handleRequest).listen(8001)

i have both index.html and login.html in my root directory..

what is the problem in above code. please help me.

Upvotes: 0

Views: 401

Answers (1)

TGrif
TGrif

Reputation: 5941

For rendering your html file, you want to use response.write(), not response.writeHead().

response.writeHead(), as his name suggests, is used to write the headers of your http response, like response.writeHead('404') if the file is not found. This is why you get the error message "Invalid status code", because the function expect a valid http code status (a number).

With response.write() you can send your file content, and response.writeHead() will be called internally to set the status (200).

Exemple:

function renderHTML(path, response) {
   fs.readFile(path, null, function(error, data) {
       if (error) {
           response.writeHead('404')
           response.end('file not found')
       } else {
           response.write(data)
       }
   })   
}

Upvotes: 2

Related Questions