Home >Web Front-end >JS Tutorial >node.js gets data from database_node.js

node.js gets data from database_node.js

WBOY
WBOYOriginal
2016-05-16 15:01:382176browse

This article needs to use node.js to create a small function to obtain data from Sqlserver and display it on the page. I will share it with you below:
app.js:

 
var sqlbll = require('./routes/sqlbll'); 
... 
app.get('/sqlbll/:ver', function(req, res){ 
 var versionId=req.params.ver; 
 //sqlbll.getData是路由中获取数据的方法, 
 //此处将第二个参数作为回调函数写入。 
 sqlbll.getData(versionId,function(data){ 
res.json(data);//发送json数据 
 }); 
}); 


//此处是路由文件 
====sqlbll.js==== 
... 
exports.getData = function(ver,back){ 
 //...此处省略1000字获取sql数据的方法 
 back(jsondata) 
} 

Next, just use the get method to request directly on the page. Of course, the post method has a similar principle.

var express = require('express'); 

var app = express(); 

app.configure(function() {

 //默认情况下Express并不知道该如何处理该请求体,因此我们需要增加bodyParser中间件,用于分析

 //application/x-www-form-urlencoded和application/json

 //请求体,并把变量存入req.body。我们可以像下面的样子来“使用”中间件[这个保证POST能取到请求参数的值]:

 app.use(express.bodyParser());

});



//处理POST请求

//name和email是POST请求域中的参数名

app.post('/hello', function(req, res) {

.......

});

Also, I found that when the textarea control changes its text and html attributes, the value still maintains the original value,
This feature has puzzled me for a while.

Let me share another example with you. nodejs obtains specific data table information. The specific content is as follows

var mysql = require('mysql');
var conn = mysql.createConnection({
 host: 'localhost',
 user: 'root',
 password: '123456',
 database:'mysql',
 port: 3306
});
var tempArr = new Array(); 
conn.connect();
conn.query("show tables",function(err,results)
{
 if(err)
 {
 throw err; 
 }
 
 if(results)
{ 
  for(var i = 0; i < results.length; i++)
 {
   tempArr[i] = results[i]; 
   var a = tempArr[i];
   console.log(typeof(results[i]));
   console.log(a); 
   var temp = "";
   temp+=a.Tables_in_mysql;
  console.log("temp"+i+" "+temp);
 conn.query("select * from"+ " "+ temp,function selectCb(err,result,fields){
  if(err)
   {
    throw err;
   }
     console.log("数据表:" + results[i]);
     console.log(fields);
      });
 }
}  
})

The above is the entire content of this article, I hope it will be helpful to everyone’s study.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn