首页 > 其他分享 >uni-app:配置访问接口时的跨域(hbuilderx: 3.6.18)

uni-app:配置访问接口时的跨域(hbuilderx: 3.6.18)

时间:2023-02-12 15:58:18浏览次数:63  
标签:跨域 18 app 14781 js item vendors api chunk

一,未配置跨域时的报错信息:

Access to XMLHttpRequest at 'http://api.lhdtest.net/item/list' from origin 'http://localhost:8081' has been blocked by CORS policy: 
No 'Access-Control-Allow-Origin' header is present on the requested resource. 15:00:59.629 chunk-vendors.js:14781 GET http://api.lhdtest.net/item/list net::ERR_FAILED 200 (OK) l @ chunk-vendors.js:14781 (anonymous) @ chunk-vendors.js:14781 O @ chunk-vendors.js:14781 (anonymous) @ chunk-vendors.js:14781 (anonymous) @ chunk-vendors.js:14781 getItem @ item.vue:19 click @ pages-item-item.js:54 invokeWithErrorHandling @ chunk-vendors.js:4196 invoker @ chunk-vendors.js:4521 invokeWithErrorHandling @ chunk-vendors.js:4196 invoker @ chunk-vendors.js:4517 original._wrapper @ chunk-vendors.js:9405 15:00:59.629 item.vue:26 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'statusCode') at eval (item.vue:26:1)

说明:刘宏缔的架构森林是一个专注架构的博客,地址:https://www.cnblogs.com/architectforest

         对应的源码可以访问这里获取: https://github.com/liuhongdi/
         或: https://gitee.com/liuhongdi

说明:作者:刘宏缔 邮箱: [email protected]

 二,代码:

<template>
    <view>
        <button style="width:700rpx;" type="primary" @click="getItem">访问接口</button>
    </view>
</template>

<script>
    export default {
        data() {
            return {
                
            }
        },
        methods: {
            getItem(){
               uni.showToast({
                                   title:"已点击了按钮"
                               });
            uni.request({
                url:'/api/item/list',
                method:'get',
            }).then((result)=>{
                let [error,res] = result;
                //result将返回一个数组[error,{NativeData}]
                if(res.statusCode === 200){
                    console.log(res.data);
                }
                if(res.statusCode === 404){
                    console.log('请求的接口没有找到');
                }
            })
            },
        }
    }
</script>

<style>

</style>

三,配置跨域

编辑manifest.json->选择"源码视图"->增加h5一栏的配置如下:

 内容:

    "h5":{
        "devServer" : {
                    "https" : false,
                    "disableHostCheck":true,
                    "proxy" : {
                        "/api" : {
                            "target" : "http://api.lhdtest.net", //域名
                            "changeOrigin" : true,
                            "secure" : false,
                            "pathRewrite" : {
                                "^/api" : ""
                            }
                        }
                    }
                }
    },

四,测试效果:

已可返回接口的数据,如图:

 五,查看hbuilderx的版本:

 

 

 

   

标签:跨域,18,app,14781,js,item,vendors,api,chunk
From: https://www.cnblogs.com/architectforest/p/17113907.html

相关文章