[英]Node.js Doesn't Execute DB Function From Browser
I have installed Node.js server with the Apache server via proxy mod and it starts fine. 我已经通过proxy mod将Node.js服务器与Apache服务器一起安装,并且一切正常。 When I call the server.js file from console like:
node /var/www/project/node/server.js
I get the running notification message which is: "ok, server is running" 当我从控制台喜欢叫server.js文件:
node /var/www/project/node/server.js
我得到的运行通知消息是:“好了,服务器正在运行”
And when I go to browser and point to the server.js http://example.com/node/
I get status 200 and it works. 当我转到浏览器并指向server.js
http://example.com/node/
状态为200,并且可以正常工作。
The problem, the function test is executed only when I start the server.js from console, but when I request server.js from browser or via AJAX call, then the function test is not executed. 问题是,仅当我从控制台启动server.js时才执行功能测试 ,但是当我从浏览器或通过AJAX调用请求server.js时,则不执行功能测试 。 I notice that through the database entries.
我注意到通过数据库条目。
I would greatly appreciate your feedback. 非常感谢您的反馈。 My code is below:
我的代码如下:
var http=require('http');
var mysql = require('mysql');
var util = require('util');
var url = require('url');
var connection = mysql.createConnection({
host : 'localhost',
user : 'xxx',
password : 'xxx',
database : 'db_test', //mysql database to work with (optional)
});
connection.connect(); //connect to mysql
var server=http.createServer(function(req,res){
res.end('Connected');
});
server.on('listening',function(){
console.log('ok, server is running');
});
server.listen(9000);
function test(){
var s = new Date().getTime();
connection.query('INSERT INTO table_test.emails (email) VALUES ("'+s+'")',function(err, result) {});
}
test();
Thanks. 谢谢。
The code in app.js
is run when you start the server with node /var/www/project/node/server.js
(The entire file is not run for each request, unlike PHP). 当您使用
node /var/www/project/node/server.js
启动服务器时,将运行app.js
的代码(与PHP不同, 不是为每个请求都运行整个文件)。 You're telling node to listen on port 9000 and execute whatever's in your createServer
callback when it receives a request. 您要告诉节点侦听端口9000并在收到请求时执行
createServer
回调中的所有操作。 Thus, you need to put the call to test()
inside your createServer
callback for it to work.: 因此,您需要将对
test()
的调用放在createServer
回调中,以使其正常工作。
var server=http.createServer(function(req,res){
test();
res.end('Connected');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.