本人寫的不復(fù)雜,適合萌新刨摩。
原文地址:https://blog.csdn.net/qq_39051175/article/details/99678556
因為是從我在csdn論壇上發(fā)表的這文章復(fù)制過來的寺晌,因此代碼每一行前面的空格被去掉了(簡書的問題)世吨,
建議復(fù)制代碼在你的編輯器里看,本文代碼都是切實可行的呻征,不會出現(xiàn)運行不了的問題耘婚。
mongodb或者mysql數(shù)據(jù)庫都可以使用陆赋,文件頭部的注釋取消即可沐祷!
復(fù)制過去用的話,記得改ajax請求的url: “http://192.168.0.76:8089/test_post”(這是我的地址和路徑)攒岛,你需要改成你自己的哦@盗佟!
不要糾結(jié) 我給變量起名很low 我有嚴重的起名困難癥T志狻K急!挠进!
/**
* a Static Server
* nodejs進程守護工具 pm2 了解一下
*/
const express = require('express');
// 這里是使用mongodb的
// const mongodb = require('mongodb');
// const MongoClient = mongodb.MongoClient;
// 這里使用mysql的
const mysql = require('mysql');
// const url = require('url');
//body-parser是非常常用的一個express中間件,作用是對post請求的請求體進行解析誊册。
const bodyParser = require('body-parser'); //用于獲取post請求參數(shù)的
let urlencodedParser = bodyParser.urlencoded({ //用于獲取post請求參數(shù)的
extended: false
})
let app = express();
//解決跨域
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With");
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
if(req.method == "OPTIONS") {
res.send(200);
} else {
next();
}
});
//設(shè)置靜態(tài)文件目錄
app.use(express.static('./'));
/* 一個測試 */
//獲取post請求參數(shù)? 需要用到一個中間件领突,頂上有加載這個
app.post('/test_post',urlencodedParser, (req, res) => {
console.log(req.body,req.originalUrl)
res.send(req.body);
})
//獲取get請求參數(shù)
app.get('/test_get', (req, res) => {
var num = 200;
//res.send('連接成功,這段字符串是node.js服務(wù)器返回的數(shù)據(jù)',num) //逗號隔開是設(shè)置隨著數(shù)據(jù)一起返回的狀態(tài)碼 比如200(成功) 500(服務(wù)器出錯)之類的案怯。
//推薦下面這么寫,把設(shè)置狀態(tài)碼跟發(fā)送數(shù)據(jù)分開
//res.status(200);
//res.send('連接成功君旦,這段字符串是node.js服務(wù)器返回的數(shù)據(jù)' + num) //加號隔開是返回這個數(shù)字作為數(shù)據(jù)
console.log(req.query,req.originalUrl)
res.send(req.query);
})
/* 一個測試 */
//注冊
app.get('/zhuce123', (req, res) => {
var pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: '',
port: 3307,
database: 'vuedata',
multipleStatements: true
? ? });
? ? console.log(req.query.yonghum);
? ? var sql1 =`insert into yonghubiao (usname, password) values ('${req.query.yonghum}', '${req.query.xinmima}')`
pool.query(sql1, function(error, rows) {
res.send(req.query.yonghum);
});
})
//登陸
app.get('/denglu123', (req, res) => {
var pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: '',
port: 3307,
database: 'vuedata',
multipleStatements: true
? ? });
? ? // console.log(req.query.yonghum);?
? ? var sql1 =`select * from yonghubiao where usname='${req.query.yonghum}' and password = '${req.query.xinmima}' limit 1`;
pool.query(sql1, function(error, rows) {
? ? ? ? console.log(rows.length);
? ? ? ? if(rows.length != 0){
? ? ? ? ? ? res.send("1");
? ? ? ? }else{
? ? ? ? ? ? res.send("0");
? ? ? ? }
});
});
//修改密碼
app.get('/xiugai123', (req, res) => {
var pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: '',
port: 3307,
database: 'vuedata',
multipleStatements: true
});
// var sql = ;
pool.query(`update yonghubiao set password='${req.query.xinmima}' where usname='${req.query.yonghum}'`, function(error, rows) {
res.send("1");
console.log(req.query);
});
});
//? 下面注釋部分是操作mongodb數(shù)據(jù)庫的
// //登陸
// app.post('/login', urlencodedParser, (req, res) => {
// let {
// name,
// mima
// } = req.body;
// MongoClient.connect("mongodb://localhost:27017/", function(err, database) {
// if(err) throw err;
// let db = database.db('xcy');
// let yhb = db.collection('yhb'); //切換到具體的集合
// yhb.findOne({
// username: name,
// password: mima
// }, (err, result) => {
// if(result) {
// // 登錄成功后,給前端發(fā)送用戶表示:token
// res.send({
// code: 1,
// data: result,
// msg: 'ok'
// })
// } else {
// res.send({
// code: 0,
// data: [],
// msg: 'fail'
// })
// }
// });
// database.close();
// });
// });
// //用戶列表
// app.get('/hqyh', (req, res) => {
// var pool = mysql.createPool({
// host: 'localhost',
// user: 'root',
// password: '',
// port: 3307,
// database: 'xcy',
// multipleStatements: true
// });
// pool.query('select * from yonghubiao', function(error, rows) {
// res.send(rows);
// });
// });
// //修改密碼
// app.get('/xiugai', (req, res) => {
// var pool = mysql.createPool({
// host: 'localhost',
// user: 'root',
// password: '',
// port: 3307,
// database: 'xcy',
// multipleStatements: true
// });
// // var sql = ;
// pool.query(`update yonghubiao set password='${req.query.xinmima}' where usname='${req.query.yonghum}'`, function(error, rows) {
// res.send("");
// console.log(req.query);
// });
// });
// //刪除
// app.get('/shanchu', (req, res) => {
// var pool = mysql.createPool({
// host: 'localhost',
// user: 'root',
// password: '',
// port: 3307,
// database: 'xcy',
// multipleStatements: true
// });
// // var sql =;
// pool.query(`DELETE FROM yonghubiao where usname= '${req.query.yonghum}'`, function(error, rows) {
// res.send("刪除成功");
// console.log(req.query.yonghum);
// });
// });
// //添加
// app.get('/tianjia', (req, res) => {
// var pool = mysql.createPool({
// host: 'localhost',
// user: 'root',
// password: '',
// port: 3307,
// database: 'xcy',
// multipleStatements: true
// });
// console.log(req.query);
// var sql = `insert into yonghubiao (usname, password) values ('${req.query.yonghum}', '${req.query.xinmima}')`;
// pool.query(sql, function(error, rows) {
// res.send("添加成功");
// });
// });
// //商品列表
// app.get('/splb', (req, res) => {
// var pool = mysql.createPool({
// host: 'localhost',
// user: 'root',
// password: '',
// port: 3307,
// database: 'xcy',
// multipleStatements: true
// });
// pool.query('select * from goods', function(error, rows) {
// res.send(rows);
// });
// });
// //修改商品列表
// app.get('/xiugaigood', (req, res) => {
// var pool = mysql.createPool({
// host: 'localhost',
// user: 'root',
// password: '',
// port: 3307,
// database: 'xcy',
// multipleStatements: true
// });
// var sql = `
// update goods set goodname='${req.query.goodming}' where id='${req.query.goodid}';
// update goods set jiage='${req.query.goodjiage}' where id='${req.query.goodid}';
// update goods set goodxiangqing='${req.query.goodzhonglei}' where id='${req.query.goodid}';
// update goods set tupianlujing='${req.query.goodtupianlujing}' where id='${req.query.goodid}';
// update goods set jieshao='${req.query.goodjieshao}' where id='${req.query.goodid}';
// update goods set shouchu='${req.query.goodshouchu}' where id='${req.query.goodid}';
// update goods set rongliang='${req.query.goodrongliang}' where id='${req.query.goodid}';
// update goods set id='${req.query.goodnewid}' where id='${req.query.goodid}';
// `;
// pool.query(sql, function(error, rows) {
// res.send("");
// console.log(req.query);
// });
// });
// //刪除good
// app.get('/shanchugood', (req, res) => {
// var pool = mysql.createPool({
// host: 'localhost',
// user: 'root',
// password: '',
// port: 3307,
// database: 'xcy',
// multipleStatements: true
// });
// // var sql =;
// pool.query(`DELETE FROM goods where id= '${req.query.goodid}'`, function(error, rows) {
// res.send("刪除成功");
// console.log(req.query.goodid);
// });
// });
// //添加商品
// app.get('/tianjiagood', (req, res) => {
// var pool = mysql.createPool({
// host: 'localhost',
// user: 'root',
// password: '',
// port: 3307,
// database: 'xcy',
// multipleStatements: true
// });
// console.log(req.query);
// var sql = `insert into goods (goodname, id,jiage,goodxiangqing,tupianlujing,jieshao,shouchu,rongliang) values ('${req.query.goodming}', '${req.query.goodnewid}','${req.query.goodjiage}','${req.query.goodzhonglei}','${req.query.goodtupianlujing}','${req.query.goodjieshao}','${req.query.goodshouchu}','${req.query.goodrongliang}')`;
// pool.query(sql, function(error, rows) {
// res.send("添加成功");
// });
// });
//監(jiān)聽某個端口
app.listen(8089, () => {
console.log("監(jiān)聽成功,服務(wù)器運行ing,端口:8089")
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
html,
body {
width: 100%;
height: 100%;
}
#btn {
width: 100px;
height: 100px;
margin: 0 auto;
display: block;
margin-top: 35%;
transform: translateY(-50%);
}
#btn2 {
width: 100px;
height: 100px;
margin: 0 auto;
display: block;
margin-top: 15%;
transform: translateY(-50%);
}
#txt {
width: 360px;
margin: 0 auto;
display: block;
padding: 10px;
background-color: bisque;
}
</style>
</head>
<body>
<button type="button" id="btn">發(fā)送btn</button>
<button type="button" id="btn2">發(fā)送btn2</button>
<div id="txt">xxc </div>
<script src="common.js" type="text/javascript" charset="utf-8"></script>
<script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
var btn = document.getElementById("btn");
var btn2 = document.getElementById("btn2");
var txt = document.getElementById("txt");
btn.onclick = function(e) {
var ajax = new XMLHttpRequest();
//如果是get傳參,用字符串模版寫在URL里吧
ajax.open('POST', 'http://192.168.0.76:8089/test_post');
ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
//原生ajax發(fā)送數(shù)據(jù) 要寫出下面這個格式,要緊湊,不要留空格(不然JSON.parse會出問題)
ajax.send("name=yyy&abc=123"); //攜帶數(shù)據(jù)到服務(wù)器
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var res = JSON.parse(ajax.responseText);
console.log(res);
txt.innerHTML = (res.name +" "+res.abc);
}
}
}
// jquery版本
$("#btn2").click(function() {
//get
$.ajax({
type: "get",
url: "http://192.168.0.76:8089/test_get",
data: {
name: '覺得可以的話點個贊嘲碱,關(guān)注一下吧'
},
success: function(res) {
console.log(res)
$("#txt").html(res.name);
}
});
//post
// $.ajax({
// type: "post",
// url: "http://192.168.0.76:8089/test_post",
// data: {
// name: 'qwe'
// },
// success: function(res) {
// $("#txt").html(res.name);
// }
// });
});
</script>
</body>
</html>