以下為通過node.js連線本機mysql資料庫的方法:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'xxxx',//此處的xxxx替換為你的mysql登入使用者名稱
password : 'xxxx',//此處的xxxx替換為你的mysql登入密碼
database : 'xxxx',//此處的xxxx替換為你要連線database名稱
socketPath : '/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock',
port:3306
});
connection.connect(function(err) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
console.log('connected as id ' + connection.threadId);
});
這裡的重點是要配置socketPath,否則會報以下這個錯:
error connecting: Error: connect ECONNREFUSED
不好意思 上面的是我从网上找的,照着写改来改去没起作用~~ 依然连不上
最后解决办法是,
在服务器搞MYSQL服务,搭建数据库,或者是内网其他电脑起一个MYSQL服务,这边调用
MAC本地代码 不需要添加socketPath,即可完美调用本地nodejs接口
简单版代码如下
var express = require('express');
var app = express();
const routes = require('./routers');
const index=require('./routers/index');
app.get('/', (req, res) => res.send('App is working'));
// app.use('/', routes);
// app.use('/api/idToken', routes);
app.use('/api/index',index);
app.get('/aa', (req, res) => {
res.send('hello')
// res.sendFile(__dirname + '/dist/index.html')
})
app.listen(5000, () => {
console.log("server up");
});
module.exports = {
app
};
完整版可参考代码如下
app.js
const express=require('express');
// const bodyParser=require('body-parser');
const session = require('express-session')
var MySQLStore = require('express-mysql-session')(session);
//创建web服务器
var server=express();
var options = {
host: '22.22.12.122',
port: 3306,
user: 'root',
password: 'root',
database: 'cake'
};
var sessionStore = new MySQLStore(options);
//引入路由模块
const cors=require('cors');
// const index=require("./routes/index");
const userRouter=require('./routers/user.js');
const cartRouter=require('./routers/cart.js');
const details=require('./routers/detail.js');
const product=require('./routers/product');
const index=require('./routers/index');
const pics=require('./routers/pics');
const login=require('./routers/login');//本接口仅供测试使用
const find=require('./routers/find');
const kind=require('./routers/kind');
const captcha=require('./routers/captcha');
const portal=require('./routers/portal');
//托管静态资源到public下;
server.use(express.static('public'));
server.use(express.static('dist'));
//跨域请求cors
server.use(cors
(
{
origin:"*" ,
// origin:"http://localhost:8080" ,
// origin:"http://localhost:4200" ,
// origin:"http://127.0.0.1:5500" ,
credentials: true
}
)
);
// server.writeHead(200,{"Access-Control-Allow-Credentials":true});
server.use(express.json())
server.use(express.urlencoded({
extended:false
}));
//session 启用会话中间件,用来保存用户登录状态以及验证码
server.use(session({
name: 'sessionId',
resave: true,
saveUninitialized: true,
secret: 'APP_SESSION_SECRET',
store: sessionStore // 将会话存到数据库
}))
server.use('/api/user',userRouter);
server.use('/api/cart',cartRouter);
server.use('/api/product',product);
server.use('/api/details',details);
server.use('/api/index',index);
server.use('/api/pics',pics);
// server.use('/api/login',login);本接口仅供测试使用
server.use('/api/find',find);
server.use('/api/kind',kind);
server.use('/api/captcha',captcha);
server.use('/api/portal',portal);
// server.get('*', (req, res) => {
// res.sendFile(__dirname + '/dist/index.html')
// })
// server.get('/aa', (req, res) => {
// res.send('hello')
// // res.sendFile(__dirname + '/dist/index.html')
// })
// 异常处理器
server.use((req,res,next,err)=>{
console.log(err.message)
res.sendStatus(500);
})
server.listen(3006, () => {
console.log("server up");
});
pool.js
const mysql=require('mysql');
//创建连接池对象
// var pool=mysql.createPool({
// host:'localhost',
// port:'3306',
// user:'root',
// password:'',
// database:'cake',
// connectionLimit:20
// });
var pool=mysql.createPool({
host: '22.222.12.122',
port: 3306,
user: 'root',
password: 'root',
database:'cake',
connectionLimit:20
});
//到处连接池对象
module.exports=pool;
路由文件举例如下:
./routers/index
const express = require("express");
const router = express.Router();
const pool = require("../pool");
//一次查询返回4条数据
router.get("/", (req, res) => {
var status = req.query.status;
var output = {
product: {}
}
if (status !== undefined) {
var sql1 = `select * from cake_index_product where index_status=?`;
pool.query(sql1, [status], (err, result) => {
if (err) console.log(err);
output.product = result;
// console.log(output);
// console.log("haha1");
res.send(output);
})
}else{
res.send(output);
console.log(444)
}
})
//一次查询返回多条数据
router.get("/insale", (req, res) => {
var status = req.query.insale;
var output = {
product: {}
}
if (status !== undefined) {
var sql1 = `select * from cake_index_product where index_sale_new=?`;
pool.query(sql1, [status], (err, result) => {
if (err) console.log(err);
output.product = result;
res.send(output);
})
}else{
res.send(output);
// console.log(444)
}
})
//首页产品一次性展示+轮播图查询
router.get("/all", (req, res) => {
var output = {
carouselItems:{},
product: {},
pics:{},
kinds:{}
}
var sql1 = `select * from index_img `;
pool.query(sql1,(err, result) => {
if (err) console.log(err);
output.carouselItems = result;
var sql2 = `select * from cake_index_product `;
pool.query(sql2,(err, result) => {
if (err) console.log(err);
output.product = result;
var sql3 = `select * from product_pic `;
pool.query(sql3,(err, result) => {
if (err) console.log(err);
output.pics = result;
var sql4 = `select * from product_kinds `;
pool.query(sql4,(err, result) => {
if (err) console.log(err);
output.kinds = result;
res.send(output);
})
})})
})
})
// 測試接口aa
router.post("/scan/collect", (req, res) => {
console.log('wolaila11')
let emp_no = req.body.emp_no;
let emp_name = req.body.emp_name;
let card_time = req.body.card_time;
let qrcode = req.body.qrcode;
var output = {
error:0,
message:'success'
}
var err = {
error:1,
message:'參數有誤或者缺失參數'
}
if(emp_no&&emp_name&&card_time&&qrcode){
res.send(output);
}else{
res.send(err);
}
})
// 測試接口
//一次查询返回多条数据post
router.post("/postStatus", (req, res) => {
console.log('wolaila')
var status = req.body.status;
var output = {
product: {},
lalala:'woshiceshi'
}
if (status !== undefined) {
var sql1 = `select * from cake_index_product where index_sale_new=?`;
pool.query(sql1, [status], (err, result) => {
if (err) console.log(err);
output.product = result;
res.send(output);
})
}else{
res.send(output);
// console.log(444)
}
})
//首页产品轮播图查询
router.get("/img", (req, res) => {
console.log('/img')
var output = {
carouselItems:{}
}
var sql1 = `select * from index_img `;
pool.query(sql1,(err, result) => {
console.log('進入SQL')
if (err) console.log(err);
output.carouselItems = result;
res.send(output);
})
})
module.exports = router;