节点js文件执行

时间:2013-08-28 10:52:11

标签: javascript node.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");

强文 任何人都可以,请告诉我我在哪里犯了错误

3 个答案:

答案 0 :(得分:2)

问题是您目前没有写任何内容来回复请求。

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");

答案 1 :(得分:1)

要扩展我对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安装它。这是express API documentation

答案 2 :(得分:0)

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

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");