[英]Node js file execution
我有一個示例節點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();
等方法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");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.