1. 程式人生 > >node+mysql+ajax+javascript搭建一套服務介面,實現前後臺數據請求

node+mysql+ajax+javascript搭建一套服務介面,實現前後臺數據請求

node+mysql+ajax+javascript搭建一套服務介面,實現前後臺數據請求

效果圖如下所示:

啟動服務
get請求
查詢mysql資料庫

express介紹

Express 基於 Node.js 平臺,快速、開放、極簡的 web 開發框架。

Web 應用

Express 是一個基於 Node.js 平臺的極簡、靈活的 web 應用開發框架,它提供一系列強大的特性,幫助你建立各種 Web 和移動裝置應用。

API

豐富的 HTTP 快捷方法和任意排列組合的 Connect 中介軟體,讓你建立健壯、友好的 API 變得既快速又簡單。

效能

Express 不對 Node.js 已有的特性進行二次抽象,我們只是在它之上擴充套件了 Web 應用所需的基本功能。

node.js 更適合做後端API

node.js 的非同步非阻塞模式使其非常適合做後端API,可以大幅度提高介面的抗壓能力。

後端介面常見形式 - JSON

node搭建服務

$ npm install --save express
$ npm install --save path

node配置

// app.js

const express = require('express');
const path = require('path');

const app = express();

app.get('/', function (reg, res) {
  const obj = {
    name: 'hcoder',
    version: 1.1
  }
  res.json(obj);
});

const server = app.listen(3000, function () {
  console.log('run http://localhost:3000');
});

mysql模組安裝

$ npm install --save mysql

mysql配置

app.js中新增mysql配置

// app.js

const body_parser = require('body-parser');

function getDb() {
  const mysqlHost = 'localhost';
  const mysqlUser = 'root';
  const mysqlPwd = 'root';
  const mysqlDb = 'model_abc';
  const mysql = require('mysql');
  const conn = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'root',
    database: 'model_abc'
  });
  conn.connect();
  return conn;
};

app.use(body_parser.urlencoded({
  extended: false
}));

app.get('/user', function (reg, res) {
  const db = getDb();
  db.query('select * from model_abc.emp;', null, function (error, result) {
    console.log(error);
    const obj = {
      status: 0,
      data: result
    }
    res.json(obj);
  })
});

可能出現的問題

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is there

解決方法:

// app.js

//設定跨域訪問
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();
});

 

完整程式碼如下所示:

配置檔案

// app.js

const express = require('express');
const path = require('path');
const body_parser = require('body-parser');

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();
});

function getDb() {
  const mysqlHost = 'localhost';
  const mysqlUser = 'root';
  const mysqlPwd = 'root';
  const mysqlDb = 'model_abc';
  const mysql = require('mysql');
  const conn = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'root',
    database: 'model_abc'
  });
  conn.connect();
  return conn;
}

app.use(body_parser.urlencoded({
  extended: false
}));

app.get('/', function (reg, res) {
  const obj = {
    name: 'hcoder',
    version: 1.1
  }
  res.json(obj);
})

app.get('/user', function (reg, res) {
  const db = getDb();
  db.query('select * from model_abc.emp;', null, function (error, result) {
    console.log(error);
    const obj = {
      status: 0,
      data: result
    }
    res.json(obj);
  })
})

const server = app.listen(3000, function () {
  console.log('run http://localhost:3000');
})

 

入口檔案

<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>node-mysql-ajax-javascipt</title>
	<link rel="stylesheet" href="">
	<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
	<h1>node-mysql-ajax-javascipt</h1>
	<h5 id="main"></h5>
</body>
</html>

 

main.js 原生請求

 

$.ajax({
    type: 'get',
    url: 'http://localhost:3000/user',
    data: {
        username: 'admin'
    },
    dataType: 'json',
    success: function(res) {
        console.log(res);
    },
    error: function(err) {
        console.log(err)
    }
});

$.ajax({
    type: 'post',
    url: 'http://localhost:3000/user',
    data: {
        username: 'admin'
    },
    dataType: 'json',
    success: function(res) {
        console.log(res);
    },
    error: function(err) {
        console.log(err)
    }
});

 啟動後臺服務

$ node app.js

GET請求,node.js獲取GET引數方式

// var username = req.query.username;

app.get('/user', function (req, res) {
    var username = req.query.username;
    res.json({status: 0, data: [{name: username}]});
});

POST請求,node.js獲取POST引數方式

// var username = req.body.username;

app.post('/user/post', function (req, res) {
    var username = req.body.username;
    res.json({status: 0, data: [{name: username}]});
});