一: 鏈接數據庫node
一、啓動node(配置以下)mysql
var express = require('express')
var bodyParser = require("body-parser")
var 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()
})
// 這兩行是post獲取參數(repress已分離body-parser組建)
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
//app.use('/upload', express.static('upload'))
app.use('/', require('./test.js'))
app.listen(3000, ()=> {
console.info('啓動成功')
})
二、鏈接mysql,鏈接數據表(建立test.js,上面要應用)ios
var express = require('express')
var router = express.Router()
var mysql = require('mysql')
var multiparty = require('multiparty')
var fs = require("fs")
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '123',
database: 'jay',
port: '3306'
})
connection.connect()
/*經過id搜索用戶*/
router.get('/query', function(req, res, next) {
connection.query(`select * from one where id=${req.query.userId}`, function(error, results, fields) {
if (error) {
console.info('error')
res.send(error)
} else {
res.send(results)
}
})
})
2、定義接口(接口名字是text.js本身定義)sql
import http from 'axios'
export default {
// 獲取用戶
getUser(param = {}) {
return http.get('api/user', {params: param})
},
// 查詢用戶
serachUser(param = {}) {
return http.get('api/query', {params: param})
},
// 登陸
userLogin(param = {}) {
return http.get('api/createUser', {params: param})
},
// 註冊用戶
addNewUser(params = {}) {
return http.post('api/addNewUser', params)
},
// 刪除用戶
deleteUser(id) {
return http.delete(`api/delete?userId=${id}`)
},
// 添加用戶
addUser(params = {}) {
return http.post('api/add', params)
},
// 修改用戶
updateUser(params = {}) {
return http.post('api/update', params)
}
}
3、angualr代理接口(在項目自定義文件),target(node監聽地址),pathRewrite(api表明這個地址,就是接口文檔的api)數據庫
{
"/api": {
"target": "http://localhost:3000",
"secure": "false",
"changeOrigin": "true",
"pathRewrite": { "^/api": "" }
}
}
4、在頁面使用express
import http from '../../api/user';
getData() {
let param = {
pageIndex: this.page,
pageSize: 10,
type: this.filter.type ? this.filter.type : null,
value: this.filter.value ? this.filter.value : null
}
http.getUser(param).then(r => {
this.userData = r.data.list
this.totalPages = r.data.total
}).catch(r => {})
}
5、親測有效,很差之處,請指教json