Home > OS >  hello world in nodejs, http not defined
hello world in nodejs, http not defined

Time:10-24

i tried to run a hello world command in nodejs, but something wrong have happened, could you help me?

http.createServer(function(req, res){
  res.writeHead(200, {'Content-Type': 'text/plain' });
  res.end('Hello World \n');
}).listen(8080, '127.0.0.1');
~ $ node server.js
/data/data/com.termux/files/home/server.js:1
http.createServer(function(req, res){
^

ReferenceError: http is not defined
    at Object.<anonymous> (/data/data/com.termux/files/home/server.js:1:1)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:79:12)
    at node:internal/main/run_main_module:17:47

CodePudding user response:

You have not created a variable called http. Also you have to create few more things before you call that http.createserver function

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

This is the complete code you should use.

CodePudding user response:

Before having used the http module, you will have to import it first. Add the import statement before using it:

let http = require("http");

Please make sure you have this statement written!

  • Related