uniAPP跨域問題解決

利用node.js搭建服務(wù)端

一、新建項目目錄并且利用node.js初始化項目 (截圖)

image.png

二、新建一個入口文件 index.js (截圖)

image.png

三、安裝一個express依賴 (截圖)

image.png

如果安裝太慢,建議將npm registry更改為淘寶鏡像。

1、臨時使用

npm --registry https://registry.npm.taobao.org install express

2、永久使用

npm config set registry https://registry.npm.taobao.org

配置后可通過下面方式來驗證是否成功:

npm config get registry
image.png

四、配置入口文件(index.js)并啟用服務(wù)器

1、配置入口文件(index.js)

//(1)引入express
const express=require("express"); 

//(2)實例化
const app=express(); 

//(3)監(jiān)聽一個端口3000
app.listen(3000,()=>{//為了監(jiān)聽服務(wù)正在運行,在控制臺打印一個內(nèi)容
    console.log("----------api 3000-------------")
})

//(4)請求一個路由 "/api/list"
app.get("/api/list",(req,res)=>{
    var arr = ["北京","上海","廣州","深圳","安徽合肥"];
    res.json(arr);   //返回請求結(jié)果
})

啟動服務(wù)端(命令截圖)

image.png

這里使用 node-dev命令啟動服務(wù),如果沒有安裝,可先使用命令全局安裝一下,“npm i node-dev -g” 。

訪問測試(截圖)

image.png

拓展:從APP項目(前端)如何訪問服務(wù)器?

說明:

APP項目地址及端口是:localhost:8081
服務(wù)器地址及端口是:localhost:3000
地址或者端口不同,就會涉及跨域問題。解決跨域問題,可從服務(wù)器端或者項目前端解決。

1、demo.vue 代碼如下:

<template>
    <view class="content">
        <h1>demo頁面</h1>
        
        <view class="btn">
            <button type="primary" @click="myClick">請求數(shù)據(jù)</button>
            <text>從node服務(wù)器上請求數(shù)據(jù),只要域名或者ip不同或者端口號不同,都涉及<text class="orangered">跨域</text>問題。</text>
        </view>
        
        <!-- 將拿到的數(shù)據(jù)渲染到頁面,循環(huán)遍歷數(shù)組 -->
        <view>
            <text  v-for="(item,index) in list" :key="index">{{item}}</text>
        </view>
    </view>
    
</template>

<script>
    export default {
        data() {
            return {
                list:[] //城市列表
            }
        },
        methods: {
            myClick(){
                uni.request({
                    url:"http://localhost:3000/api/list",
                    success:res=>{
                        console.log(res);
                        var list = res.data; 
                        this.list = list;
                    }
                })
            }
        }
    }
</script>

<style>
    .content{
        padding: 20rpx;
    }
    .btn{
        margin: 20rpx 0;
    }
    h1{
        background-color: yellow;
        text-align: center;
    }
    .orangered{
        background-color: orangered;
        color: white;
        padding: 0 10rpx;
    }
    text{
        display: inline-block;
        background-color: deepskyblue;
        padding: 10rpx 20rpx;
        margin: 20rpx;
        border-radius: 10rpx;
        color: white;
    }
</style>


運行到微信開發(fā)工具,點擊請求按鈕,控制臺打印輸出結(jié)果?!晒Λ@取數(shù)據(jù)

image.png

運行到H5端,報錯!因為存在跨域問題。如下圖所示:

image.png

解決跨域問題的兩種方法:

1、服務(wù)器端解決方法

步驟:

(1)服務(wù)器端安裝 cors

image.png
image.png

(2)配置index.js文件(引入cors并使用cors)

image.png

node項目的index.js 代碼如下:

//1引入express
const express=require("express"); 

//引入 cors
const cors=require("cors");

//2實例化
const app=express(); 
app.use(cors()); //注意 cors() 有括號

//3監(jiān)聽一個端口3000
app.listen(3000,()=>{//為了監(jiān)聽服務(wù)正在運行,在控制臺打印一個內(nèi)容
    console.log("----------api 3000--------------")
})

//4請求一個路由 "/api/list"
app.get("/api/list",(req,res)=>{
    var arr=["北京","上海","廣州","深圳","安徽合肥"];
    res.json(arr); //返回請求結(jié)果
})


(3)H5端測試請求數(shù)據(jù)——成功請求到數(shù)據(jù)

image.png

注意:

因為有緩存的原因,即使服務(wù)器端關(guān)閉 cors 引入和使用,已經(jīng)訪問的數(shù)據(jù)依然能夠再次被看到??梢酝ㄟ^清除瀏覽器緩存的方法,清除 訪問到本地的數(shù)據(jù)。

2、前端解決方法—— 配置代理,解決跨域

(1)先關(guān)閉 cors 服務(wù)

image.png

(2)配置APP項目中 manifest.json 文件,設(shè)置代理規(guī)則。(參照: webpack.config.js)

image.png
image.png

注意:每次修改 manifest.json 之后都要重啟服務(wù)。

APP項目中 manifest.json文件關(guān)于H5端代碼如下:

 "h5" : {
        "title" : "H5",
        "devServer": {
            "proxy":{
                //配置代理:只要 遇到 /api 都改為  http://localhost:3000
                "/api":{
                    "target":"http://localhost:3000"
                }
            }
        }
    }

(3)重啟H5端服務(wù)(重新運行)

image.png

至此,H5端就可以順利訪問服務(wù)器的數(shù)據(jù)

但是,小程序端又又不可以訪問了,接下來繼續(xù)優(yōu)化并解決小程序端的訪問。

(4)利用平臺判斷 完善demo.vue

image.png

APP項目的demo.vue 代碼如下:

<template>
    <view class="content">
        <h1>demo頁面</h1>
        
        <view class="btn">
            <button type="primary" @click="myClick">請求數(shù)據(jù)</button>
            <text>從node服務(wù)器上請求數(shù)據(jù),只要域名或者ip不同或者端口號不同,都涉及<text class="orangered">跨域</text>問題。</text>
        </view>
        
        <!-- 將拿到的數(shù)據(jù)渲染到頁面,循環(huán)遍歷數(shù)組 -->
        <view>
            <text  v-for="(item,index) in list" :key="index">{{item}}</text>
        </view>
    </view>
    
</template>

<script>
    export default {
        data() {
            return {
                list:[] //城市列表
            }
        },
        methods: {
            myClick(){
                var url = "/api/list";  //先給 url設(shè)置默認(rèn)值
                // 平臺判斷 - 如果不是H5 則  url = "http://localhost:3000/api/list"
                // #ifndef H5   
                    var url = "http://localhost:3000/api/list"
                // #endif
                
                uni.request({
                    // url:"http://localhost:3000/api/list",
                    // url:"/api/list",
                    url:url,
                    success:res=>{ //請求成功時,執(zhí)行以下代碼
                        console.log(res);
                        var list = res.data; 
                        this.list = list;
                    },
                    fail:err=>{ //請求失敗時,執(zhí)行以下代碼
                        console.log(err)
                    }
                })
            }
        }
    }
</script>

<style>
    .content{
        padding: 20rpx;
    }
    .btn{
        margin: 20rpx 0;
    }
    h1{
        background-color: yellow;
        text-align: center;
    }
    .orangered{
        background-color: orangered;
        color: white;
        padding: 0 10rpx;
    }
    text{
        display: inline-block;
        background-color: deepskyblue;
        padding: 10rpx 20rpx;
        margin: 20rpx;
        border-radius: 10rpx;
        color: white;
    }
</style>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容