Node.js

栏目: Node.js · 发布时间: 6年前

内容简介:本demo是使用express+mySql制作一个简单的链接sql项目前准备安装node.js

本demo是使用express+mySql制作一个简单的链接sql

项目前准备

安装node.js http://nodejs.cn/

安装express http://www.expressjs.com.cn/

安装Mysql https://www.mysql.com/

项目结构初始化

第一步:首先新建express站点,这些我们新建的项目名称是expres sql,如果小伙伴们不知道express的这些指令,可以通过express –help查看(插一句,在这之前确保已经安装了 express)

第二步:进入到这个项目目录 cd sql

第三步:安装依赖 npm install

第四步:启动这个项目* & npm start,这里如果你安装了pm2,也可以使用pm2启动

第五步:命令行会提示在哪个端口监听,如果想改默认端口号,在bin文件夹下面的www文件进行修改

第六步:打开浏览器进行查看 localhost:3000(默认)

Node.js

至于文件夹里面的目是用express 生成的 http://www.expressjs.com.cn/

Node.js

首页页面+功能实现

关于系统中和用户的相关路由配置都写的routes文件夹下面的item.js中

Node.js

注意:

app.js文件中引入了routes中的item.js,var item = require('./routes/item');并且使用app.use()将应用挂载到app应用上app.use(‘/item’, itemRouter);所以在访问item这个路径时就要变成/users/item

新建html页面

<!DOCTYPE html>

<html>

<head>

<title></title>

</head>

<body>

</body>

</html>

<script src=" https://cdn.bootcss.com/jquer... ;></script>

<script>
    $(function(){
      $.ajax({
        url:"http://localhost:3000/item/list",
        type:'post',
        dataType:'json',
        success:function(e){
            for(var i in e){
                $('body').append("<h1>"+"<a href='id.html?id="+e[i].id+"'>"+e[i].name+"</a>"+"</h1>"+"<p>"+e[i].content+"</p>")
            }
        }
    })      
    })
</script>

现在通过在自己电脑输入 http://localhost :3000/

Node.js

routes文件夹下item.js下面输入注册的路由

var express=require('express');//引入express 模块

var router=express.Router(); //路由

var mysql= require('mysql');//引入 mysql 模块

var connection=mysql.createConnection({ //链接数据库池

host:'localhost',

user:'root',//用户名

password:'123456'//密码 在配置mysql 的时候设置

});

Node.js

router.post('/list',function(req,res,next){

res.header('Access-Control-Allow-Origin','*')    ;

connection.query('SELECT * FROM baobei.list_table', function(err, rows, fields) {

res.send(rows)

});

})

router.post('/detail', function(req, res, next) {

var content=req.body.arr;
res.header('Access-Control-Allow-Origin','*');
connection.query("SELECT * FROM baobei.list_table WHERE id='"+content+"';", function(err, rows, fields) {
  res.send(rows);

});

});

module.exports=router;


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Letting Go of the Words

Letting Go of the Words

Janice (Ginny) Redish / Morgan Kaufmann / 2007-06-11 / USD 49.95

"Redish has done her homework and created a thorough overview of the issues in writing for the Web. Ironically, I must recommend that you read her every word so that you can find out why your customer......一起来看看 《Letting Go of the Words》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具