這次用node后端來(lái)開(kāi)發(fā)即時(shí)聊天灰粮,這篇博客將進(jìn)行前后端的接口對(duì)接炬搭。
一夺姑、創(chuàng)建項(xiàng)目
- 創(chuàng)建server文件夾墩邀,安裝express
C:\uni-app-project\server>cnpm install express --save
image.png
二、編寫(xiě)后端文件
如圖:
image.png
在安裝了express框架后盏浙,以這樣的文件結(jié)構(gòu)眉睹,首先在yike.js中寫(xiě)主體邏輯:
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => res.send('哈哈哈哈'))
//設(shè)置允許跨域訪問(wèn)該服務(wù).
app.all('*', function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
//Access-Control-Allow-Headers ,可根據(jù)瀏覽器的F12查看,把對(duì)應(yīng)的粘貼在這里就行
res.header('Access-Control-Allow-Headers', 'Content-Type');
res.header('Access-Control-Allow-Methods', '*');
res.header('Content-Type', 'application/json;charset=utf-8');
next();
});
require('./router/index')(app);
//404頁(yè)面
app.use(function (req, res, next) {
let err = new Error('Not Found');
err.status = 404;
next(err)
})
//出現(xiàn)錯(cuò)誤處理
app.use(function (req, res, next) {
res.status(err.status || 500)
res.send(err.message)
})
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
- 在router中index.js中寫(xiě):
module.exports = function (app) {
app.get('/test', (req, res) => res.send('這里是test頁(yè)面'))
}
node yike.js即可運(yùn)行程序,找到/test就能看到相關(guān)數(shù)據(jù)
三废膘、鏈接前后端接口
前端寫(xiě)入方法(這里是uniapp的請(qǐng)求方法竹海,axios同理):
uni.request({
url:'http://192.168.0.105:3000/test',
data:{},
method:'GET',
success(data){
console.log(data);
}
})
就可以對(duì)接上了
image.png