node.js 搭建http调取 mysql数据库中的值
生活随笔
收集整理的這篇文章主要介紹了
node.js 搭建http调取 mysql数据库中的值
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
首先,我們先在數(shù)據(jù)庫中創(chuàng)建兩個表t_news,t_news_type;插入數(shù)據(jù):
然后我們再寫代碼:
//加載模塊express var express = require("express"); var fs = require("fs"); //加載路徑 var url = require("url"); //加載數(shù)據(jù)庫 var mysql = require("mysql"); var app = express();app.set('view engine','ejs'); //動態(tài)路徑 app.set('views',__dirname '/views'); //靜態(tài)路徑 app.use(express.static(__dirname '/public')); //加載路由 var router = express.Router;//獲取路徑 router.get('/index',function(req,res){//創(chuàng)建連接var connection = getConnection();//查詢excuteQuery("SELECT b.news_type_id,a.title ,a.news_id,a.t_date,b.name as typename from" " t_news a JOIN t_news_type b on a.news_type_id = b.news_type_id WHERE b.news_type_id=1; ",connection,function(result){//發(fā)送指定頁面res.render('qh/views',{args:result});}) });app.use('/action',router); //獲取數(shù)據(jù) function excuteQuery(sql,connection,fun){connection.query(sql,function(error,rows){var result= "";if(error){result = {"status":"500","message":"服務器錯誤"}}else{result = {"status":"200","message":"success","data":rows}}fun(result ); }); } //獲取數(shù)據(jù)庫function getConnection (){var connection = mysql.createConnection({host: 'localhost',user: 'dzlx',password:'wm969926dzl',port: '3306',database: 'test' })connection.connect();return connection; }app.listen(3001,function afterListen(){console.log("express running ...."); })在你的網頁中插入:
?
更多專業(yè)前端知識,請上 【猿2048】www.mk2048.com
總結
以上是生活随笔為你收集整理的node.js 搭建http调取 mysql数据库中的值的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 关于React-native的介绍以及环
- 下一篇: ajax提交手机号去数据库验证并返回状态