4

我有一个示例节点 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");

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

4

3 回答 3

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");
于 2013-08-28T10:57:28.120 回答
1

为了扩展我关于alert不工作的评论,以下是您如何使用 express 来完成您所要求的事情:

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 文档

于 2013-08-28T12:41:46.263 回答
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");
于 2013-08-28T11:03:31.310 回答