nodejs安装post请求依赖:npm install express body-parser
const express = require('express');
var async = require('async');
const app = express();
//提供post请求支持
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
//数据库连接并启动连接池
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root', // 改成你自己的密码
database: 'zengyifan' // 改成你的数据库名称
});
connection.connect();
// 解决跨域请求问题
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();
});
/*----------------------------------------接口部分----------------------------------------*/
/**
* 实现多重查找并返回想要的结果,主要是async.map那个操作
*/
app.get('/getAllOrder', function (req, res) {
var sql = 'select * from torder ORDER BY create_time ASC';
//查询
connection.query(sql, function (err, result) {
if (err) {
res.send(err.message);
return;
}
async.map(result, function(item, callback) {
var sql = 'select * from consumer_goods where order_id = ?';
connection.query(sql, item.id, function(err, goods){
item.goods = goods;
console.log("item",item)
callback(null, item);
});
}, function(err,results) {
console.log("result",result)
res.send(results);//把数据返回
});
});
});
/**
* 得到post请求并处理
*/
app.post('/upLoadBlog', function (req, res) {
var title = req.body.title;
var homeworkName = req.body.homeworkName;
var homeworkId = req.body.homeworkId;
var summary = req.body.summary;
var content = req.body.content;
var userId = req.body.userId;
var userName = req.body.userName;
var avatar = req.body.avatar;
var sql = 'INSERT into blog\n' +
' (title,homework_name,homework_id,summary,content,createTime,user_id, user_name,avatar)\n' +
' values (?,?,?,?,?,now(),?,?,?)';
var sqlParams = [title, homeworkName, homeworkId, summary, content, userId, userName, avatar];
connection.query(sql, sqlParams, function (err, result) {
res.send(result);
});
});
/*----------------------------------------起服务----------------------------------------*/
var server = app.listen(8000, '127.0.0.1', function () {
var host = server.address().address;
var port = server.address().port;
console.log("地址为 http://%s:%s", host, port);
});