使用jQuery進行數據交互
前端提交/獲取ajax數據
var data = {
"name": "test",
"test": "test",
};
$.ajax({
type: 'GET', // 請求類型
url: /your/url/, //請求發送到的服務器接口
data: data, // 傳輸的內容
dataType: 'json', // 傳輸的值的類型
success: function(data) { //服務器返回的數據
}
});
后台獲取前端傳輸的數據
- 開啟服務器
// 開啟服務器
const express = require("express");//需要安裝express包方便
const app = express();
const bp = require("body-parser");
app.use(bp.urlencoded({ extended: true }));
app.listen(8080, () => console.log("服務器連接成功"));//設置本地服務器端口號
const router = express.Router();
// 全局設置跨域請求頭
app.all("*", function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://127.0.0.1:5501"); //前端的服務器端口
res.header("Access-Control-Allow-Headers", "*");
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");
res.header("Access-Control-Allow-Credentials", "true");
next();
});
- 連接數據庫
2.1 連接MongoDB數據庫MongoDB是一個介於關系數據庫和非關系數據庫之間的數據庫,無序事先創建好數據庫內文件夾,表,字段.可在服務器內代碼進行創建
2.2 連接 MySQL 數據庫const mongoose = require("mongoose");//連接數據庫,需要先安裝mongoose包 mongoose.connect("mongodb://localhost/mondb", {//mondb:數據庫內分類文件夾名 useNewUrlParser: true, useUnifiedTopology: true, }).then(() => console.log("數據庫連接成功")).catch((err) => console.log("數據庫連接失敗", err)); //設定集合規則 const coureseSchema = new mongoose.Schema({ ip: String,//String表示字符串格式的數據,可選擇多種格式. time: String, text: String, }); const lyb = mongoose.model("lyb", coureseSchema);//創建數據表格,lyb表示表格名,coureseSchema表示表內字符的名字集合跟格式規則 lyb.find({}).exec(function(err, data) {//{}查找的條件 console.log(data);//返回查找到的數據 });MySQL關系型數據 調用數據必須先創建好表名,字段格式才能進行操作
let mysql = require("mysql"); //引入mysql數據庫 須先安裝mysql包 let option = { lost: "localhost", //數據庫端口類型 port: "3306", //端口號 user: "root", //用戶登錄名 password: "199905", //密碼 database: "mydb", //表名 }; let connection = mysql.createConnection(option); connection.connect(function(err) { if (err) { console.log("數據庫連接失敗", err); } else { console.log("數據庫連接成功"); connection.query("select * from article ", function(err, data) {//select * from article:數據庫查找語法 console.log(data);//數據庫內返回的內容 } } } - 服務器獲取前端傳輸的數據
3.1 post請求
3.2 GET請求app.post("/index",function(req,res){ console.log(req.body);//前端傳輸過來的數據 res.json(data)//回傳到接口的json數據,方便前端進行獲取數據 })
3.3 結合數據庫使用方法app.get("/index",function(req,res){ console.log(req.query);//前端傳輸過來的json數據 res.json(data)//回傳到接口的json數據,方便前端進行獲取數據 })app.post("/list", function(req, res) { // 操作數據庫 lyb.find(req.body).exec(function(err, data) {//find(req.body):查找所有符合req.body內的數據 res.json(data);//查找到的數據進行傳輸到接口方便前端進行調用 }); });
