【发布时间】:2012-06-20 18:28:00
【问题描述】:
我是 node.js 的初学者(实际上是从今天开始的)。我不清楚其中一个基本概念,我在这里问,但在 SO 上找不到。
在网上阅读了一些教程,我编写了一个客户端和一个服务器端代码:
服务器端(比如 server.js):
var http = require('http'); //require the 'http' module
//create a server
http.createServer(function (request, response) {
//function called when request is received
response.writeHead(200, {'Content-Type': 'text/plain'});
//send this response
response.end('Hello World\nMy first node.js app\n\n -Gopi Ramena');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
客户端(比如 client.js):
var http=require('http');
//make the request object
var request=http.request({
'host': 'localhost',
'port': 80,
'path': '/',
'method': 'GET'
});
//assign callbacks
request.on('response', function(response) {
console.log('Response status code:'+response.statusCode);
response.on('data', function(data) {
console.log('Body: '+data);
});
});
现在,要运行服务器,我在终端或 cmd 提示符下输入 node server.js。 &它成功运行在控制台中记录消息&当我浏览到 127.0.0.1:1337 时还会输出响应。
但是,如何运行 client.js?我不明白如何运行客户端代码。
【问题讨论】:
-
节点是服务器端而不是客户端。看看这个。 stackoverflow.com/questions/5168451/…
-
不确定您在哪里找到了 client.js 或您期望它做什么,但这不是您可以放在浏览器中的东西。如果通过客户端,你的意思是另一个 Node.js 应用程序,当然。我认为您找到的教程是在指导您如何编写访问其他服务器上的 HTTP 资源的服务器。
-
你在哪里找到
client.js?你自己写的吗?你想达到什么目的? -
那么客户端如何与node.js服务器通信。我的意思是服务器不能只在指定的时间或基于指定的 url 输出值。
标签: node.js