自己写了一个登陆认证的API,但是程序一直调不对,路过的大神请指点下
发布于 10 年前 作者 iamsunxin 3539 次浏览 最后一次编辑是 8 年前

//loginauth.js var mysql = require(‘mysql’); var http = require(‘http’); var server= http.createServer(); var querystring = require(‘querystring’);

var connection = mysql.createConnection({ host: ‘localhost’, user: ‘root’, password: ‘’, database:‘main’, port: 3306 }); connection.connect();

//回应get方法的函数		
len=0;//字符串长度定义

var getResponse = function(req, res){ res.writeHead(200, {‘Content-Type’: ‘text/plain’}); var name = require(‘url’).parse(req.url,true).query.userName//获取用户名字 var strname=JSON.stringify(name); console.log(name); var pwd=require(‘url’).parse(req.url,true).query.password //获取用户密码 var strpwd=JSON.stringify(pwd); console.log(pwd); var select=‘select * from user where stu_account=’+connection.escape(name)+ ‘and stu_pwd=’+connection.escape(pwd); //SQL查询语句 //var select=‘select * from user where stu_account=’+connection.escape(name)+ ‘and stu_pwd=’+connection.escape(pwd); //SQL查询语句 console.log(select);

   connection.query(select,function(err1,res1){//查询结果并字符串化,得到字符串长度
   if (err1) console.log(err1);
	idstr=JSON.stringify(res1);
	console.log(idstr);
	len=idstr.length;
	console.log(len);
	});
	}
//判断len的长度返回判断数据

var judgement=function(req,res){ if(len<3){ console.log(‘failed’); res.end(‘failed’,‘utf8’); } else{ console.log(“success”); res.end(‘success’,‘utf8’); } } //request处理请求类别,对应相应的处理函数 var http = require(‘http’); requestFunction = function (req, res){
req.setEncoding(‘utf8’);//请求编码 if (req.method == ‘GET’){
getResponse(req,res);
judgement(req,res); console.log(“judgement exec1”); }
else{ return 0; } console.log(“request exec1”); } //服务器运行的一些代码 server.on(‘request’,requestFunction); server.listen(8080, “172.30.30.70”); console.log(‘http start’);

node.js控制台调试信息: 031//账号 6934105ad50010b814c933314b1da6841431bc8b//密码 select * from user where stu_account='031’and stu_pwd=‘6934105ad50010b814c933314 b1da6841431bc8b’ failed judgement exec1 request exec1 [] 2 undefined undefined select * from user where stu_account=NULLand stu_pwd=NULL failed judgement exec1 request exec1 { [Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ’stu_pwd=NULL’ at line 1] code: ‘ER_PARSE_ERROR’, errno: 1064, sqlState: ‘42000’, index: 0 } undefined

调试发现,getResponse函数被调用了两次,不知道为什么,请大神指点

2 回复

因为客户端会发送两个请求一个是浏览器自带favicon.ico请求,过滤一下就可以了!

我刚刚自己试了下 在请求判断中加入if(request.url != ‘/favicon.ico’){ //todo } 已经可以了,谢谢!

回到顶部