node.JS 如何停止永无止境的请求?
我通过express框架和node-mysql得到了这个简单的脚本。基本上,代码监听来自客户端的请求,如果有请求,它将查询数据库。然后,不用多说,它只是将消息反馈发送回客户端。
问题是,消息反馈永远不会到达客户端,因为请求永远不会关闭。您可以运行代码并查看我实际上在说什么,代码中的数据库登录是有效的。在运行之前,您需要“npm install express”和“npm install mysl”。将代码保存到文件并在nodejs中运行。然后打开浏览器输入地址localhost:4000
var mysql = require('mysql').Client,
express = require('express');
//databse work
var client = new mysql();
client.host = '112.78.2.135';
client.user = 'vietnaml_craig';
client.password = 'camera';
client.database = 'vietnaml_db';
client.connect();
var app = express.createServer();
//prepare to create server session for the user
var store = new express.session.MemoryStore;
app.use(express.cookieParser());
app.use(express.session({
secret: 'something',
store: store
}));
//tell server listen to get request from client
app.get('/', function(req, res){
client.query(
'SELECT * FROM user_cookie ',
function selectCb(err, results, fields) {
res.header('Content-Type', 'text/plain');
res.header('Access-Control-Allow-Origin', '*');
res.send('go to go');
res.end();
console.log(results);
client.end();
}
);
});
app.listen(4000);
I got this simple script ulizting express framework and node-mysql. Basically, the code listens to request from client, if there is request it will make query to database. then without further ado it just sends a message feedback back to the client.
Problem, the message feedback never go to client because the request never close. You can run the code and see what i'm actually talking about, the database login in the code is valid. Before run you need "npm install express" and "npm instal mysl". save the code to a file and run it in nodejs. Then open browser enter adress localhost:4000
var mysql = require('mysql').Client,
express = require('express');
//databse work
var client = new mysql();
client.host = '112.78.2.135';
client.user = 'vietnaml_craig';
client.password = 'camera';
client.database = 'vietnaml_db';
client.connect();
var app = express.createServer();
//prepare to create server session for the user
var store = new express.session.MemoryStore;
app.use(express.cookieParser());
app.use(express.session({
secret: 'something',
store: store
}));
//tell server listen to get request from client
app.get('/', function(req, res){
client.query(
'SELECT * FROM user_cookie ',
function selectCb(err, results, fields) {
res.header('Content-Type', 'text/plain');
res.header('Access-Control-Allow-Origin', '*');
res.send('go to go');
res.end();
console.log(results);
client.end();
}
);
});
app.listen(4000);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我刚刚运行了你的代码并注释掉了
res.end()
并且它在我的计算机上适用I just ran your code and commented out
res.end()
and it works for me on my computer