求助,关于 Express 请求 url 里的 undefined
发布于 11 年前 作者 sysudengle 7257 次浏览 最后一次编辑是 8 年前

在使用 Express 来做一个应用的时候发现每次加载页面总会去 GET 多一次当前 url,并且第二次 GET 时的 url 会变为 undefined。 比如我路由的代码为:

app.get('/index', routes.index);

第一次得到结果 GET /index,但是会多得到 GET /undefined

又比如路由的代码是

app.get('/home/:username', routes.home);

假设我 url 是 /home/test,第一次 GET 是正常的,后面多出一次 GET /home/undefined。 调试了很久还是看不出问题所在,求各位帮忙分析下有什么可能,感激不尽!

3 回复

你试一下直接用curl 请求一下 ?

如果用curl 正常的话,可能是客户端请求了些什么东西

能否把你的app和路由代码都贴出来一下。 就这样很难分析问题出在哪里了。

curl是正常的,我在登录之前都是只访问一次,登录之后都会多出来一个访问,app的代码如下,谢谢!


/**
 * Module dependencies.
 */

var express = require('express');
var routes = require('./routes');
var http = require('http');
var path = require('path');
//mongodb
var MongoStore = require('connect-mongo');
var settings = require('./settings');
//var flash = require('connect-flash');
var MongoStore = require('connect-mongo')(express);

var app = express();
//new add layout
var expressLayouts = require('express-ejs-layouts');


// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(expressLayouts);
//app.use(flash());
//new add layout
//app.set('layout', 'myLayout');

app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.bodyParser({uploadDir: './public/images/dog'}));//uploaded tmp img dir
//app.use(express.router.routes);
app.use(express.cookieParser('your secret here'));

app.use(express.static(path.join(__dirname, 'public')));

//use mongodb
app.use(express.cookieParser());
app.use(express.session({
	secret: settings.cookieSecret,
	cookie: {maxAge: 1000*60*60},//one hour lifespan
	store: new MongoStore({
		db: settings.db
	})
}));

//app.router should be after cookie and session use
app.use(app.router);
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

app.get('/', routes.index);
app.get('/index', routes.index);
app.get('/home/:username', routes.home);
//app.get('/home1/:username', routes.home1);
app.get('/info', routes.info);
app.get('/login', routes.login);
app.post('/login', routes.doLogin);
app.get('/reg', routes.reg);
app.post('/reg', routes.doReg);
app.get('/logout', routes.logout);

app.post('/search', routes.search);
app.post('/followuser', routes.followUser);
app.post('/deletetemprelation', routes.deleteTempRelation);
app.post('/deletefollow', routes.deleteFollow);

app.get('/myfans', routes.getFans);
app.get('/myfollows', routes.getFollows);

app.post('/sendmsg', routes.sendmsg);
app.post('/updateinfo', routes.updateInfo);

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

//chat function
var io = require('socket.io').listen(8080);  
io.set('log level', 1);  
global.USERS_NAME = {};  
var userSocketList = [];
var userNameList = [];

io.sockets.on('connection', function (socket) {  
  io.sockets.emit('connect',{hello:'boy'});  
  
  socket.on('private message', function (from,to,msg) {  
    console.log('I received a private message by ', from, ' say to ',to, msg);  
    if(to in USERS_NAME){  
		console.log('emit!');
		//console.log(USERS_NAME[to]);
		console.log(USERS_NAME);
        USERS_NAME[to].emit('to'+to,{from: from, to: to, message:msg});  
        USERS_NAME[from].emit('to'+from,{from: from, to: to, message:msg});
    }  
	else
 	{
        USERS_NAME[from].emit('to'+from,{from: from, message:to + "不在线!"});
  	}
  });  
  socket.on('new user',function(data){  
     if(data in USERS_NAME){  
          
     }else{  
        var nickname = data;  
        USERS_NAME[nickname]= socket;  
		userSocketList.push(socket);
		userNameList.push(nickname);
		console.log('newUser' + nickname);
     }  
//	 console.log(USERS_NAME);
//     console.info(USERS_NAME);  
  });  
  socket.on('disconnect', function () {  
	var index = userSocketList.indexOf(socket);
	userSocketList.splice(index, 1);
	delete USERS_NAME[userNameList[index]];
	userNameList.splice(index, 1);
	//console.log(user);
	console.log('----------');
    io.sockets.emit('user disconnected');  
    console.info(USERS_NAME);  
  });  
}

路由代码:


/*
 * GET home page.
 */

var fs = require('fs');
var crypto = require('crypto');
var User = require('../models/user.js');
var Msg = require('../models/msg.js');
var Relation = require('../models/relation.js');
var imgDogDir = '/images/dog/';

var requireLogin = function(req, res)
{
	if(req.session.user == null)
		res.redirect('/login');
	global.dogImgPath = req.session.user.img;
};

module.exports.index = function(req, res){
	requireLogin(req, res);
	var username = req.session.user.name;
	var msgs = null;
	var otherMsgs = null;
	console.log(USERS_NAME);
	console.log('gggggggggggggg');
	Msg.get(null, function(err, msgsParam){
		if(!err)
		{
			msgs = msgsParam;
		}

  		res.render('index', { title: 'Index', username: username, msgs: msgs});
	});
  	//res.render('index', { title: 'Express' });
};

module.exports.login = function(req, res){
	res.render('login', { title: 'login' });
};

module.exports.doLogin = function(req, res){
	var md5 = crypto.createHash('md5');
	var password = md5.update(req.body.password).digest('base64');
	User.get(req.body.username, function(err, user) { 
		if (!user) { 
			//req.flash('error', '用户不存在'); 
			return res.redirect('/login'); 
		} 
		if (user.password != password) { 
			//req.flash('error', '用户口令错误'); 
			return res.redirect('/login'); 
		} 
		req.session.user = user; 
		//req.flash('success', '登入成功'); 
		//res.redirect('/home/' + user.name);
		/*fs.exists(imgDogDir + user.name + '.png', function(err){
			if(!err) global.dogImgPath = imgDogDir + 'default.png';
			else global.dogImgPath = imgDogDir + user.name + '.png';
			console.log(err);
			console.log(global.dogImgPath);
		});*/
		global.dogImgPath = user.img;
		res.redirect('/index');
	}); 
};

module.exports.reg = function(req, res){
	var mongodb = require('mongodb');
	var server = new mongodb.Server('localhost',27017,{auto_reconnect:true});
	var db = new mongodb.Db('mydb',server,{safe:true});

	db.open(function(err,db){
		if(!err)
	{  
		console.log('connect');
	}else{
		console.log(err);
	}  

	});
	res.render('reg', { title: '用户注册' });
};

module.exports.doReg = function(req, res){
	//res.render('reg', { title: 'register successfully' });
	console.log("doReg!!!!!!!!!!!!");
	if (req.body['password-repeat'] != req.body['password']) {
		req.flash('error', '两次输入的口令不一致');
		return res.redirect('/reg');
	}

	//生成口令的散列值
	var md5 = crypto.createHash('md5');
	var password = md5.update(req.body.password).digest('base64');
	var newUser = new User({
		name: req.body.username,
		password: password,
	});
	console.log("doReg22222222!!!!!!!!!!!!");

	//检查用户名是否已经存在
	User.get(newUser.name, function(err, user) {
		if (user)
			err = 'Username already exists.';
		if (err) {
			console.log("exist!!!!!!!!!!!!");
			//req.flash('error', err);
			return res.redirect('/reg');
		}

		//狗狗图片处理
		var tmpPath = req.files.dogImg.path;
		console.log(tmpPath);
		var imgType = (req.files.dogImg.type) == 'image/png'?'.png':'.jpg';
		var targetFile = './public/images/dog/' + newUser.name + imgType;
		console.log(req.files.dogImg.type);
		fs.rename(tmpPath, targetFile, function(err){
			if(err) throw err;

			targetFile = targetFile.slice(8);//去掉./public
			newUser.img = targetFile;
			console.log(newUser);
			newUser.save(function(err, user) {
				if (err) {
					console.log("register error!");
					//req.flash('error', err);
					return res.redirect('/reg');
				}
				req.session.user = newUser;
				console.log("Registered!!!!!!!!!!!!" + newUser);
				//req.flash('success', '注册成功');
				//res.redirect('/home/' + newUser.name);
				global.dogImgPath = targetFile;
				res.redirect('/index');
				
			});
		});
		//如果不存在则新增用户
	});
};

module.exports.logout = function(req, res){
	req.session.user = null;
	res.redirect('/login');
};


module.exports.home1 = function(req, res){
	var username = "su";
	console.log("!!!!!!!!!!!");
  	return res.render('home2', { title: 'User home', username: username});
};

module.exports.home = function(req, res){
	console.log(req.params.username);
	console.log(req.url);
	if(req.params.username == undefined)
	{
		console.log('askhdaksjdh');
		return;
	}
	else
	{
		console.log(req.params.username);
	}
	requireLogin(req, res);
	console.log('00000000000000000000');
//	var username = req.session.user.name;
	var username = req.params.username;
	var msgs = null;
	var otherMsgs = null;
	Msg.get(username, function(err, msgsParam){
		if(!err)
		{
			msgs = msgsParam;
		}
		User.get(username, function(err, user) {
			console.log(username);
			console.log('!!!!!!!!!!!');
			console.log(user.img);
			if (err) {
				console.log("exist!!!!!!!!!!!!");
				//req.flash('error', err);
				
			}
			User.get(username, function(err, user){
				console.log(user);
				if(user)
				{
  					return res.render('home', { title: 'User home', username: username, msgs: msgs, user: user});
				}
				else
				{
  					return res.render('home', { title: 'User home', username: username, msgs: msgs});
				}
			  	return res.render('home', { title: 'User home', username: username, msgs: msgs, otherImg: user.img});
			});
		});
	});
};


module.exports.info = function(req, res){
	requireLogin(req, res);
	var username = req.session.user.name;
	User.get(username, function(err, user){
		console.log(user);
		if(user)
		{
			return res.render('info', { title: '狗狗信息', user: user, username: username});
		}
		else
		{
			return res.render('info', { title: '狗狗信息', err: true, username: username});
		}
	});
};

module.exports.search = function(req, res){
	var username = req.body.username;
	console.log(username);
	console.log("+++++++++++++++++++++++++");
	requireLogin(req, res);
	var info = {
		title: "Search",
		view: "search",
		userListQuery: { name: { $regex: username, $options: 'i'} }
	};
	getUserList(req, res, info);
	//User.getList(username, function(err, users) {
	//	if (users)
	//		err = 'user exists';
	//	if (err) {
	//		console.log("exist!!!!!!!!!!!!");
	//		//req.flash('error', err);
	//		console.log(users);
	//		Relation.getMap({ user1: req.session.user.name }, function(err, follows){
	//			console.log('~~~get Friend');
	//			console.log(req.session.user.name);
	//			console.log(users);
	//			console.log(follows);
	//			if(!err)
	//			{
	//				var deleteIndex = -1;
	//				users.forEach(function(user, index){
	//					if(user.name in follows)
	//					{
	//						users[index].follow = true;
	//						console.log(user.name);
	//					}
	//					if(user.name == req.session.user.name)
	//					{
	//						deleteIndex = index;
	//						console.log("iiiiiiiiiiiiiiiiii");
	//					}
	//				});
	//				if(deleteIndex != -1)
	//				{
	//					delete users[deleteIndex];
	//				}
	//			}
	//			console.log(users);
	//			return res.render('search', { title: 'Search', users: users, username: req.session.user.name });
	//		});
	//	}
	//	else {
	//		return res.render('search', { title: 'Search', error: true });
	//	}
	//});
};

getUserList = function(req, res, info)
{
	User.getList(info.query, function(err, users) {
		if (users)
			err = 'user exists';
		if (err) {
			console.log("exist!!!!!!!!!!!!");
			//req.flash('error', err);
			console.log(users);
			Relation.getMap({ user1: req.session.user.name }, function(err, follows){
				console.log('~~~get Friend');
				console.log(req.session.user.name);
				console.log(users);
				console.log(follows);
				if(!err)
				{
					var deleteIndex = -1;
					users.forEach(function(user, index){
						if(user.name in follows)
						{
							users[index].follow = true;
							console.log(user.name);
						}
						if(user.name == req.session.user.name)
						{
							deleteIndex = index;
							console.log("iiiiiiiiiiiiiiiiii");
						}
					});
					if(deleteIndex != -1)
					{
						delete users[deleteIndex];
					}
				}
				console.log(users);
				return res.render(info.view, { title: info.title, users: users, username: req.session.user.name });
			});
		}
		else {
			return res.render(info.view, { title: info.title, error: true });
		}
	});
}

module.exports.getFans = function(req, res){
	requireLogin(req, res);
	var username = req.session.user.name;
	var fansQuery = {user2: username};

	Relation.getMap(fansQuery, function(err, fans){
		if(err)
		{
			return res.render('myFans', {title: "myFans", err: true });
		}
		
		var followsQuery = {user1: username};
		Relation.getMap(followsQuery, function(err, follows){
			if(err)
			{
				return res.render('myFans', {title: "myFans", err: true });
			}
			var users = [];
			for(var fan in fans)
			{
				var isFollow = false;
				if(fan in follows) isFollow = true;
				users.push({name: fan, follow: isFollow});
			}
			return res.render('myFans', {title: "myFans", users: users, username: username });
		});
	});
};

module.exports.getFollows = function(req, res){
	requireLogin(req, res);
	var username = req.session.user.name;
	var query = {user1: username};

	Relation.getMap(query, function(err, follows){
		if(err)
		{
			return res.render('myFollows', {title: "myFollows", err: true });
		}
		
		var users = [];
		for(var name in follows)
		{
			users.push({name: name, follow: true});
		}
		return res.render('myFollows', {title: "myFollows", users: users, username: username });
	});
	
};

module.exports.sendmsg = function(req, res){
	console.log("send suck!");
	console.log(req.body.user);
	var newMsg = new Msg({
		user: req.body.user,
		content: req.body.content,
		time: req.body.time,
		good: 0,
	});
	newMsg.save(function(err, msg){
		if (err)
		{
			console.log("error while writing to db");
			return res.jsonp({stat: false});
		}
		return res.jsonp({stat: true});
	});
};

module.exports.updateInfo = function(req, res){
	requireLogin(req, res);
	var username = req.session.user.name;
	var data = { dog:
		{
			gender: req.body.gender,
			type: req.body.type,
			place: req.body.place,
		}
	};
	console.log(data);
	User.update(username, data, function(err, result){
		if(err)
		{
			console.log("error while update info");
			return res.jsonp({stat: false});
		}
		return res.jsonp({stat: true});
	});
};

module.exports.followUser = function(req, res){
	requireLogin(req, res);
	//new Follow
	var relation = new Relation({ 
		user1: req.session.user.name,
		user2: req.body.user2, 
	});
	relation.save(function(err, relation) {
		if (err)
		{
			console.log("follow suc to db");
			return res.jsonp({stat: false});
		}
		return res.jsonp({stat: true});
	});
};

module.exports.deleteTempRelation = function(req, res){

};

module.exports.deleteFollow = function(req, res){
	requireLogin(req, res);
	//delete Follow
	var relation = new Relation({ 
		user1: req.session.user.name,
		user2: req.body.user2, 
	});
	//first parameter is isTemp
	relation.deleteRelation(false, function(err, relation) {
		if (err)
		{
			console.log("remove follow suc to db");
			return res.jsonp({stat: false});
		}
		return res.jsonp({stat: true});
	});

};
//module.exports = function(app) {
//	app.get('/', function(req, res) {
//		res.render('index', {
//			title: '首页'
//		});
//	});
//
//	app.get('/reg', function(req, res) {
//		res.render('reg', {
//			title: '用户注册',
//		});
//	});
/
回到顶部