Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js: TypeError: object is not a function

Tags:

node.js

I have a weird error:

var http = require("http");
var request = require("request");

http.createServer(function(request, response) {
    response.writeHead(200, {"Content-Type": "text/plain"});

    request('http://www.google.com', function (error, response, body) {
        if (!error && response.statusCode == 200) {
            console.log(body) // Print the google web page.
        }
    });
    response.end();
}).listen(8888);

The idea is for it to listen as a webserver, and then do a request. But this is what I get as error:

    request('http://www.google.com', function (error, response, body) {
    ^
TypeError: object is not a function
    at Server.<anonymous> (/Users/oplgkim/Desktop/iformtest/j.js:8:2)
    at Server.EventEmitter.emit (events.js:98:17)
    at HTTPParser.parser.onIncoming (http.js:2056:12)
    at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:120:23)
    at Socket.socket.ondata (http.js:1946:22)
    at TCP.onread (net.js:525:27)

What am I doing wrong? I installed request, so that's not it :)

like image 297
R0b0tn1k Avatar asked Mar 23 '14 17:03

R0b0tn1k


People also ask

How do you solve the is not a function error in JavaScript?

The TypeError: "x" is not a function can be fixed using the following suggestions: Paying attention to detail in code and minimizing typos. Importing the correct and relevant script libraries used in code. Making sure the called property of an object is actually a function.

Is not a function in console?

To solve the "console. log is not a function" error, make sure to place a semicolon between your console. log call and an immediately invoked function expression and don't define any variables named console in your code.


1 Answers

Access to the request global variable is lost as you have a local variable with the same name. Renaming either one of the variables will solve this issue:

var http = require("http"); var request = require("request");

http.createServer(function(req, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
    request('http://www.google.com', function (error, response, body) {
      if (!error && response.statusCode == 200) {
        console.log(body) // Print the google web page.
      }
    })
  response.end();
}).listen(8888);
like image 151
Tim Cooper Avatar answered Oct 15 '22 03:10

Tim Cooper