从Node.js开始...集成Express的问题

时间:2018-07-23 08:14:08

标签: node.js

如前所述,我正在尝试加快Node.js的速度。以下代码似乎可以正常工作(除了“ site”由于某种原因而未被识别)……其余的都可以正常工作:

var http = require('http');
var url = require('url');
var querystring = require('querystring');


var server = http.createServer(function(req, res){
var params = querystring.parse(url.parse(req.url).query);
var MyURL = url.parse(req.url).search;  //example returns "?year=2017&month=february" 
var site = url.parse(req.url).host;  //example returns "localhost:8080"

res.writeHead(200, {"Content-Type": "text/plain"});
if ('lat' in params && 'lng' in params){
res.write('Coordinates passed ' + params['lat'] + ' ' + params['lng']);
console.log(MyURL);
res.write('Page Default: ' + site);
console.log('Page default ' + site);
}
else {
res.write('Coordinates not passed');
}

res.end();
});
server.listen(8080)

...但是,当我添加Express模块​​时...我的命令似乎被忽略了...如下所示:

var http = require('http');
var url = require('url');
var querystring = require('querystring');
var express = require('express');

var app = express();

var server = http.createServer(function(req, res){
var params = querystring.parse(url.parse(req.url).query);
var MyURL = url.parse(req.url).search;  //example returns "?year=2017&month=february" 
var site = url.parse(req.url).host;  //example returns "localhost:8080"

res.writeHead(200, {"Content-Type": "text/plain"});
if ('lat' in params && 'lng' in params){
res.write('Coordinates passed ' + params['lat'] + ' ' + params['lng']);
console.log(MyURL);
res.write('Page Default: ' + site);
console.log('Page default ' + site);
}
else {
res.write('Coordinates not passed');
}

app.get('/', function(req, res) {

res.setHeader('Content-Type', 'text/plain');
res.write('You are connected to a Test');

console.log('This is a test...!');

});

app.get('/index.html', function(req, res) {
var page = url.parse(req.url).pathname;  //example returns "index.html"

res.write('You are connected to the index.html page on this test site!');
res.write('Page Default: ' + page);
console.log(page);

});

app.use(function(req, res, next){
res.setHeader('Content-Type', 'text/plain');
res.send(404, 'Page cannot be found!');
});

res.end();
});
server.listen(8080)

“应用”均不存在。函数似乎被解雇了...有人可以解释我在这里不明白的内容吗?我提前谢谢你。问候...!

1 个答案:

答案 0 :(得分:0)

我认为是因为您需要使用app.listen而不是服务器。

Look at the example here