npm init
npm install express-generator -g
express
npm install ejs
更改app.js
var ejs = require('ejs');
app.engine('html',ejs.__express);
app.set('view engine','html');
node自动更新服务
npm install -save supervisor
//package.json中更改
"scripts": {
"start": "supervisor ./bin/www", // 原命令 start: node./bin/www
},
//注意,这里是 -save, 之前安装 -g ,在使用的时候报错
//因为用 -g 的时候是全局安装,并不能保存到dependencies中
"dependencies": {
"cookie-parser": "~1.4.3",
"debug": "~2.6.9",
"express": "~4.16.0",
"http-errors": "~1.6.2",
"jade": "~1.11.0",
"morgan": "~1.9.0",
"supervisor": "^0.12.0" // 使用 -g 时 不能自动生成
}
连接数据库
npm install mysql
var mysql = require('mysql');
const app = express();
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By",' 3.2.1');
res.header("Content-Type", "application/json;charset=utf-8");
next();
});
// 创建数据库连接对象
// const mysql = require('mysql');
const conn = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'Sa123',
database: 'world',
multipleStatements: true
});
// 查询出所有数据
app.get('/api/getList',(req, res) => {
const sqlStr = 'select * from city'
conn.query(sqlStr, (err,results) => {
if(err) return res.json({
err_code: 1,
message: '数据不存在',
affextedRows: 0
})
res.json({
err_code: 200,
message: results,
affextedRows: results.affextedRows
})
})
});
app.listen(3001, () => {
console.log('正在监听端口3001,http://localhost:3001');
})
js部分
$(function(){
console.log(1);
//get请求
$.ajax({
type:'get',
url:'http://localhost:3001/api/getList',
success:function(data){
console.log(data);
},
error:function(err){
console.log(err)
}
})
})
写接口
node部分
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By",' 3.2.1');
res.header("Content-Type", "application/json;charset=utf-8");
next();
});
var questions = [
{
data: 'zjt',
num: 123,
age: 18
},
{
data: 'fh',
num: 456,
age: 19
}
];
app.get('/123', function(req, res) {
res.status(200);
res.json(questions)
});
var server = app.listen(3001, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http: //', host,port);
})
js部分
let html = ``;
$.ajax({
type: 'GET',
url: 'http://localhost:3001/123',
processData: false,
success: function(data) {
for (let i = 0; i < data.length; i++) {
html +=`
<li>data:${data[i].data}</li>
<li>num:${data[i].num}</li>
<li>age:${data[i].age}</li>
`
}
$('#Lists').append(html);
},
error: function() {
console.log('error');
}
})
html部分
<div id="Lists"></div>