美文网首页
uniapp设置代理 接入 node

uniapp设置代理 接入 node

作者: 鹿简luz | 来源:发表于2022-06-22 16:47 被阅读0次

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)
                }
            })
前端打印内容,成功获取到数据

相关文章

网友评论

      本文标题:uniapp设置代理 接入 node

      本文链接:https://www.haomeiwen.com/subject/loduvrtx.html