2014-02-21 47 views
0

nodejs基于javascript,但有些方法,如alert(),writeln(),...等在nodejs中不起作用。JavaScript方法不能在nodejs中工作

var http = require('http'); 

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

response.end(''+alert('server running')+''); // alert() not working here. 
}).listen(8124); 

console.log('Server running at http://127.0.0.1:8124/'); 

如何在nodejs程序中使用这些方法。

+3

'alert'是浏览器中的'window'对象的一部分。使用'console.log'登录到终端 – ashley

回答

1

这些是您试图呼出的浏览器功能。您无权访问像windowdocument这些全局对象,因为这些对象只是浏览器特定的。

重写的例子是:

var http = require('http'); 

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

    console.log('This will be written in your console'); 
    response.end('server running'); // The response output 
}).listen(8124); 

console.log('Server running at http://127.0.0.1:8124/'); 
1

这些都是浏览器特定的方法,当然它们不能在节点中工作。

改为尝试console.log(whatYouNeedToLog)

1

你不能。它们在NodeJS的背景下没有任何意义。

如果您想要在浏览器中运行这些功能,请向浏览器发送一个带有嵌入式JS的HTML文档,而不是纯文本文档。