0

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.

1 Answer 1

2

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)
       }
   })   
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.