編寫接口連接并查詢數(shù)據(jù)庫(kù)數(shù)據(jù)(二)
1.通過postman測(cè)試post請(qǐng)求
新建一個(gè)接收post的路由
//根據(jù)post的id查詢
var selId='select * from list where id=?'
//響應(yīng)post
router.post('/list', function(req, res, next) {
var id=req.body.id; //通過req的body拿到post的id
pool.getConnection(function(err,suc){
suc.query(selId,[id],function(err,result){
if(result){ //數(shù)據(jù)庫(kù)有返回?cái)?shù)據(jù)
result={ //返回?cái)?shù)據(jù)與格式
code:200,
msg:'獲取單個(gè)測(cè)試列表成功',
data:result
}
}
res.json(result); //響應(yīng)返回json數(shù)據(jù)
suc.release(); //關(guān)閉數(shù)據(jù)庫(kù)連接
})
})
});
測(cè)試結(jié)果

id為1的數(shù)據(jù)

id為2的數(shù)據(jù)
2.Vue(axios發(fā)送post請(qǐng)求)
安裝axios&element-ui
cnpm install axios --save //是一個(gè)基于 promise 的 HTTP 庫(kù)
cnpm install element-ui --save //餓了么前端出品的一套 Vue.js 后臺(tái)組件庫(kù)
打開main.js引入
//element
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.use(ElementUI)
//axios
import axios from 'axios'
axios.defaults.baseURL='http://localhost:3000'; //設(shè)置一個(gè)類似base_url的請(qǐng)求路徑
global.axios=axios; //設(shè)置一個(gè)全局axios便于調(diào)用
打開helloword.vue
//html部分
<el-table class="user_table"
:data="userList"
border>
<el-table-column
fixed
prop="Id"
label="用戶ID">
</el-table-column>
<el-table-column
prop="u_name"
label="姓名">
</el-table-column>
<el-table-column
prop="u_phone"
label="電話">
</el-table-column>
</el-table>
//script部分
data(){
return{userList:[]} //用于接收返回?cái)?shù)據(jù)
},
mounted(){
this.get()
},
methods:{
get(){
var this_=this;
//調(diào)用最開始寫的那個(gè)接口,拉取全部數(shù)據(jù)
axios.post('/users/list',{id:1}).then(function(res){
this_.userList=res.data.data
}).catch(function(err){
console.log(err)
}) }, }
測(cè)試是否成功連接:
打開mysql
運(yùn)行node服務(wù) npm start
運(yùn)行vue npm run dev
發(fā)現(xiàn)并沒有拿到數(shù)據(jù),查看控制臺(tái)報(bào)錯(cuò)信息

報(bào)錯(cuò)信息
node服務(wù)運(yùn)行在localhost:3000端口,vue運(yùn)行在localhost:8080端口
解決方法是在node中配置cors解決不同端口的跨域問題
安裝cors
cnpm install cors --save
在app.js中引入cors并配置
//cors
var cors=require('cors');
app.use(cors({
origin:['http://localhost:8080'], //指定接收的地址
methods:['GET','POST'], //指定接收的請(qǐng)求類型
alloweHeaders:['Content-Type','Authorization'] //指定header
}))
配置完成后重啟node服務(wù) 打開vue,看到數(shù)據(jù)已經(jīng)成功拿到

獲取指定數(shù)據(jù)成功
對(duì)數(shù)據(jù)進(jìn)行一些基本操作(四)