mainfest.json -> 源码视图 中添加代理
"h5" : {
"devServer" : {
"port":8080,//本地项目运行端口
"disableHostCheck" : true,
"proxy" : {
"/api" : {
"target" : "http://192.168.10.1:3000",//本地ip + node默认暴漏的端口号
"changeOrigin" : true,
"secure" : false,
"pathRewrite":{
"^/url":"/"
}
},
"/http" : {
"target" : "http://192.168.10.1:3000",
"changeOrigin" : true,
"secure" : false
}
}
}
}
node包中routes/index.js路径配置
var express = require('express');
var router = express.Router();
router.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,OP0TIONS");
res.header("X-Powered-By", "Express");
res.header("Content-Type", "text/html; charset=UTF-8");
next();
});
router.get('/', function(req, res, next) {
res.render('index', {
title: 'Express'
});
});
//自定义接口一
router.get('/apiii/list', function(req, res, next) {
res.send({
code: 0,
data: {
list: [{
id: 1,
name: 'html'
},
{
id: 2,
name: 'css'
},
{
id: 3,
name: 'javascript'
}
]
}
})
});
//自定义接口二
router.get('/httppp/list', function(req, res, next) {
res.send({
code: 0,
data: {
name:'zhangsan',
age:30
}
})
});
module.exports = router;
apiii 和 httppp 是为了和写入 “pathRewrite” 代理的api,http做区分
页面内写入
//连接自定义端口一,代理时有pathRewrite,需要 pathRewrite + 接口名
uni.request({
url:'/url/apiii/list',
method:'GET',
success: (res) => {
console.log(res.data)
}
})
//连接自定义端口二,代理时没有pathRewrite,直接写接口名
uni.request({
url:'/httppp/list',
method:'GET',
success: (res) => {
console.log(res.data)
}
})
网友评论