Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

Error: response.write is not a function

Hey all,

I am doing the exercise Build a Simple Dynamic Site with Node.js >> Reading from Files (7:30).

When I try to run my app, I received the error response.write is not a function

below you can find all my codes

app.js

const router = require("./router.js");

// problem: We need a simple way to look at a user's bagde count and JavaScript point from a web browser

//solution: Use Node.js to perform the profile look ups and server our template via HTTP

//Create a web server
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;

http.createServer((request, response) => {
  router.home(request,response);
  router.user(request,response);
}).listen(port, hostname);
console.log(`Server running at http://${hostname}:${port}/`);

router.js

const Profile = require("./profile.js");
const renderer = require('./renderer.js');

//2. Handle HTTP route GET / and POST/ i.e. Home
function home(request,response) {
  //if the URL == "/" && GET
  if(request.url === "/"){
    response.writeHead(200,{'Content-Type': 'text/plain'});
    renderer.view('header',{},'response');
    response.write("Search\n");
    response.end("Footer\n");
  }
  //if the URL == "/" && POST
    //redirect to / :username
}
//3. Handle HTTP route GET / :username i.e. / fjordani
function user(request,response) {
  if(username.length > 0){
    //show search field
    response.writeHead(200,{'Content-Type': 'text/plain'});
    response.write("Header\n");
    response.write("Search\n");
    response.end("Footer\n");
    //get JSON from threehouse
    const studentProfile = new Profile(username);
    //on end
    studentProfile.on("end", (profileJSON) => {
      //show profile

      //store the needed values
      const values = {
        avatarUrl: profileJSON.gravatar_url,
        username: profileJSON.profile_name,
        badges: profileJSON.badges.length,
        javascriptPoints: profileJSON.points.JavaScript
      }
      //simple response
      response.write(`${values.username} has ${values.badges} badges\n`);
      response.end("Footer\n");
    });
    //on error
    studentProfile.on("error", (error) => {
      //show error
      response.write(error.message+"\n");
      response.end("Footer\n");
    });
  }

}

      // on "error"
        // show error

module.exports.home = home;
module.exports.user = user;

renderer.js

const fs = require('fs');

function view(templateName,values,response) {
  //read from the template file
  const fileContents = fs.readFileSync('./views/' + templateName + '.html');
  //Insert values into the Content

  //write out to the response
  response.write(fileContents);
}

module.exports.view = view;

What am I doing wrong?

Thanks, Felipe

3 Answers

Andrew Chalkley
STAFF
Andrew Chalkley
Treehouse Guest Teacher

Does it say which file and on what line number?

Hey Andrew,

Below is the entire error message:

Server running at http://127.0.0.1:3000/
/Users/fjordani/Desktop/learn/threehouse/JavaScript/buildASimpleDynamicSiteWithNodeJS/felipeProject/renderer.js:9
  response.write(fileContents);
           ^

TypeError: response.write is not a function
    at Object.view (/Users/fjordani/Desktop/learn/threehouse/JavaScript/buildASimpleDynamicSiteWithNodeJS/felipeProject/renderer.js:9:12)
    at Object.home (/Users/fjordani/Desktop/learn/threehouse/JavaScript/buildASimpleDynamicSiteWithNodeJS/felipeProject/router.js:9:14)
    at Server.http.createServer (/Users/fjordani/Desktop/learn/threehouse/JavaScript/buildASimpleDynamicSiteWithNodeJS/felipeProject/app.js:13:10)
    at emitTwo (events.js:106:13)
    at Server.emit (events.js:191:7)
    at HTTPParser.parserOnIncoming [as onIncoming] (_http_server.js:546:12)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:99:23)

Thanks, Felipe

Hey Andrew,

It's solved, I had forgotten to replace to update my if block

  if(request.url === "/"){
    response.writeHead(200,{'Content-Type': 'text/plain'});
    renderer.view('header',{}, response);
    renderer.view('search',{}, response);
    renderer.view('footer',{}, response);
  }

and also to handle my username variable

  const username = request.url.replace("/","");

Thanks, Felipe

Cosimo Scarpa
Cosimo Scarpa
14,047 Points

Hi there, I have the same problem. Every time that I run the page come out this error.

var Profile = require("./profile.js");
var rederer = require("./renderer.js");

// Handle HTTP route GET / and POST / i.e. Home
function home(request, response) {
  //if url  == "/" && GET
  if(request.url === "/"){
    response.writeHead(200,{'Content-Type': 'text/plain'});
    renderer.view('header',{}, response);
    renderer.view('search',{}, response);
    renderer.view('footer',{}, response);
  }
  //if url == "/" && POST
    //redirect to /:username
}

// Handle HTTP route GET /:username i.e. /cosimowise
function user(request, response) {
  //if url == "/..."
  var username = request.url.replace("/", "");
  if(username.length > 0) {
    response.writeHead(200, {'Context-Type': 'text/plain'});
    renderer.view('header', {}, response);

    //get JSON from Treehouse
    var studentProfile = new Profile(username);
      //on "end"
      studentProfile.on("end", function(profileJSON) {
        //show profile

        //Store the values witch we need
        var values = {
          avatarUrl: profileJSON.gravatar_url,
          username: profileJSON.profile_name,
          badges: profileJSON.badges.length,
          javaScriptPoints: profileJSON.points.javaScript,
        }
        //Simple response
        renderer.view('profile', values, response);
        renderer.view('footer', {}, response);
      }); 

      //on "error"
      studentProfile.on("error", function(error) {
      //show error
      renderer.view('error', {errorMessage: error.message}, response);
      renderer.view('search', {}, response);
      renderer.view('footer', {}, response);
        });
  }
}


module.exports.home = home;
module.exports.user = user;
treehouse:~/workspace$ node app.js                                                                                                 
Server running at http://<workspace-url>/                                                                                          
/home/treehouse/workspace/router.js:9                                                                                              
    renderer.view('header',{}, response);                                                                                          
    ^                                                                                                                              

ReferenceError: renderer is not defined                                                                                            
    at Object.home (/home/treehouse/workspace/router.js:9:5)                                                                       
    at Server.<anonymous> (/home/treehouse/workspace/app.js:10:10)                                                                 
    at emitTwo (events.js:106:13)                                                                                                  
    at Server.emit (events.js:191:7)                                                                                               
    at HTTPParser.parserOnIncoming [as onIncoming] (_http_server.js:546:12)                                                        
    at HTTPParser.parserOnHeadersComplete (_http_common.js:99:23)      

thank you! Cos