简体   繁体   English

如何在node.js上运行项目

[英]How to run a project on node.js

I am a beginner to node.js and i did a sample code it shown below, 我是node.js的初学者,我做了一个示例代码,如下所示,

  var http = require("http");
  var server = http.createServer(function(request,response) {
   response.writeHead(200, {
    "content-Type" : "text/html"
   });
  response.end("Hello again");
 }).listen(8888);

and when i run this file on eclise Run as ------> Node project and when i open the browser with url localhost:8888 it shows web page not availble. 当我在eclise上运行此文件时运行------>节点项目,当我用url localhost:8888打开浏览器时,它显示网页无法使用。 can u guys help me to find out. 你能帮助我找出答案吗? I already installed node.js on my system and npm alse. 我已经在我的系统和npm上安装了node.js. am i missing something? 我错过了什么吗?

There is no request or response object in the scope of your request callback. 请求回调范围内没有requestresponse对象。 You need to define them as arguments of the callback function. 您需要将它们定义为回调函数的参数。

var http = require("http");
var server = http.createServer(function(request, response) {
  response.writeHead(200, {
    "content-Type" : "text/html"
  });
  response.end("Hello again");
}).listen(8888);

You should definitely get an error though - are you sure your IDE is set up properly? 你肯定应该得到一个错误 - 你确定你的IDE设置正确吗?

You never accept the "request" variable. 你永远不会接受“请求”变量。 Below is a working version of what you're attempting. 以下是您正在尝试的工作版本。

var http = require("http");
var server = http.createServer();

server.on('request', function(request, response) {
   response.writeHead(200, {
    "content-Type" : "text/html"
   });
  response.end("Hello again");
});

server.listen(8888);

Can you please tell me where you found response object? 你能告诉我你在哪里找到了response对象吗? http.createServer return a callback function which have two arguments. http.createServer返回一个有两个参数的回调函数。 They are response and request . 他们是responserequest response use for send data/information to client and request use for get data/information from client. 响应用于向客户端发送数据/信息,并请求用于从客户端获取数据/信息。 So in your http.createServer callback function add response and request arguments. 所以在你的http.createServer回调函数中添加响应和请求参数。 After that in callback function use response object. 之后在回调函数中使用response对象。 Like this. 像这样。

var http = require("http");
var server = http.createServer(function(request, response) {
    response.writeHead(200, {
        "content-Type" : "text/html"
    });
    response.end("Hello again");
 }).listen(8888);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM