节点js文件执行

我有一个示例节点js文件,我在命令提示符下执行它,但它不是在浏览器中,

var http = require('http'); port = process.argv[2] || 8888; http.createServer(function(request,response){ response.writeHead(200, { 'Content-Type': 'text/html' }); var PI = Math.PI; exports.area = function (r) { var res1 = PI * r * r; response.end(res1, 'utf-8'); // alert(res1); return res1; }; exports.circumference = function (r) { var res2 = 2 * PI * r; response.end(res2, 'utf-8'); //alert(res2); return res2; }; }).listen(parseInt(port, 10)); console.log("file server running at\n => hostname " + port + "/\nCTRL + C to shutdown"); 

强大的文本任何人都可以,请告诉我,我犯了什么错误

问题是你目前没有写任何东西来响应请求。

response.write()

你也正在使用像alert(); 它们是浏览器方法,但是当前运行的代码是在服务器端执行的。

目前你只能声明方法,不要调用任何东西。

这个例子应该工作:

 var http = require('http'); port = process.argv[2] || 8888; http.createServer(function(request, response) { response.writeHead(200, { 'Content-Type': 'text/html' }); var PI = Math.PI; area = function(r) { var res1 = PI * r * r; response.write('Area = ' + res1); // alert(res1); return res1; }; circumference = function(r) { var res2 = 2 * PI * r; response.write('circumference = ' +res2); //alert(res2); return res2; }; area(32); response.write(' '); circumference(23); response.end(); }).listen(parseInt(port, 10)); console.log("file server running at\n => hostname " + port + "/\nCTRL + C to shutdown"); 

为了扩展我对alert不起作用的评论,下面是你如何使用快递来做你想问的问题:

 var express = require('express'); var app = express(); app.configure(function(){ // I'll let you read the express API docs linked below to decide what you want to include here }); app.get('/area/:radius', function(req, res, next){ var r = req.params.radius; res.send(200, { area: Math.PI * r * r }); }); app.get('/circumference/:radius', function(req, res, next){ var r = req.params.radius; res.send(200, { circumference: 2 * Math.PI * r }); }); http.createServer(app).listen(8888, function(){ console.log('Listening on port 8888'); }); 

这假设你已经在package.json中包含了“express”,并用npm install来安装它。 这里是快速API文档 。

问题是你还没有结束响应对象,所以你的请求继续下去,最终失败,你需要结束响应对象(如果需要一些数据)

 var http = require('http'); port = process.argv[2] || 8888; http.createServer(function(request,response){ var PI = Math.PI; exports.area = function (r) { var res1 = PI * r * r; alert(res1); return res1; }; exports.circumference = function (r) { var res2 = 2 * PI * r; alert(res2); return res2; }; response.end('hello'); }).listen(parseInt(port, 10)); console.log("file server running at\n => hostname " + port + "/\nCTRL + C to shutdown");