CORS政策已阻止从来源[本地]访问[服务器]上的XMLHttpRequest

时间:2019-12-16 04:19:41

标签: api cordova cors

我在该项目中使用Cordova + Vuejs + Webpack,并且在我的项目中使用cordova-plugin-advanced-http进行发布,然后在加载函数时遇到此错误。

我已在下面附加了相关文件。请帮助我。

这是我在项目中拥有的config.xml文件:

<?xml version='1.0' encoding='utf-8'?>
<widget id="com.example.template" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <preference name="android-minSdkVersion" value="19"/>
    <preference name="DisallowOverscroll" value="true"/>
    <hook src="hooks/hookers.js" type="before_prepare"/>
    <hook src="hooks/beforedep.js" type="before_deploy"/>
    <name>Cordova - Framework7 - Vue - Webpack Template</name>
    <description>
        Brand new cordova project!
    </description>
    <author email="dev@cordova.apache.org" href="http://cordova.io">
        Apache Cordova Team
    </author>
    <content src="index.html"/>
    <plugin name="cordova-plugin-whitelist" spec="1"/>
    <access origin="*"/>
    <allow-intent href="http://*/*"/>
    <allow-intent href="https://*/*"/>
    <allow-intent href="tel:*"/>
    <allow-intent href="sms:*"/>
    <allow-intent href="mailto:*"/>
    <allow-intent href="geo:*"/>
    <platform name="android">
        <allow-intent href="market:*"/>
    </platform>
    <platform name="ios">
        <splash src="res/screen/ios/Default@2x~universal~anyany.png"/>
        <allow-intent href="itms:*"/>
        <allow-intent href="itms-apps:*"/>
    </platform>
    <allow-navigation href="*"/></widget>

这是执行功能的示例文件:

    <template>
        <f7-page class="home">
            <f7-navbar title="WeCafe"></f7-navbar>

            <f7-block>
                <f7-segmented raised tag="p">
                    <f7-button large @click="changeType('pickup')" :class="{'button-active':pickup}" icon-f7="bag_fill" icon-size="16px">Pick Up</f7-button>
                    <f7-button large @click="changeType('dinein')" :class="{'button-active':dinein}" icon-material="local_dining" icon-size="16px">Dine In</f7-button>
                </f7-segmented>
            </f7-block>

            <f7-block>
                <f7-list>
                    <f7-list-input type="select" defaultValue="all">
                        <option value="all">All</option>
                        <option value="rate">Rating</option>
                        <option value="order">Highest Order</option>
                    </f7-list-input>
                </f7-list>
            </f7-block>

            <f7-block>
                <f7-card>
                    <f7-card-content :padding="false">
                        <f7-list medial-list>
                            <f7-list-item v-for="shop in shops" :key="shop.id">
                                <img slot="media" src="https://cdn.framework7.io/placeholder/fashion-88x88-4.jpg" width="44"/>
                                <p class="shop-details">
                                    {{shop.name}}
                                    <br>
                                    <small>
                                        <span class="rate">
                                            <f7-icon f7="star_fill" size="16px" color="orange"></f7-icon>4.7
                                        </span>
                                        <span class="sales">20 sold</span>
                                    </small>
                                </p>
                            </f7-list-item>
                        </f7-list>
                    </f7-card-content>
                </f7-card>
            </f7-block>

        </f7-page>
    </template>

    <style type="text/css" lang="scss">
    .home{
        .segmented-raised{
            .button{
                .icon{
                    top: -2px!important;
                    padding-right: 5px!important;
                }
            }
        }

        .card{
            margin-left: 0;
            margin-right: 0;

            .shop-details{
                margin: 0;

                .rate{
                    margin-right: 5px;
                }

                .sales{
                    margin-left: 5px;
                }
            }

        }
    }
</style>

<script>
    export default {
        components: {

        },
        data() {
            return {
                pickup: false,
                dinein: false,
                type: '',
                shops: []
            }
        },
        created: function() {
            const params = {
                method: 'get',
                data: {  },
                headers: { 'Authorization': 'hgQbNvPefnn9qnDwQQK03FCPGW5GQdrB8wUKo7DSeNul5fl7nUpJ2mtRjuWF' }
            };

            cordova.plugin.http.sendRequest('http://wecafe.uat.wepost.com.my/api/shops', params, function(response) {
                this.shops = response.data.shops;
            }, function(response) {
                console.log(response.error);
            });
        },
        methods: {
            changeType(type){
                if(type == 'pickup'){
                    this.pickup = true
                    this.dinein = false
                    this.type = type
                }else if(type == 'dinein'){
                    this.dinein = true
                    this.pickup = false
                }
                this.type = type
            }
        }
    };
</script>

这是我的cordova项目的index.html文件:

<!DOCTYPE html><html><head><meta http-equiv="content-security-policy" content="default-src *; script-src &apos;self&apos; data: &apos;unsafe-inline&apos; &apos;unsafe-eval&apos; http://127.0.0.1:8081 http://192.168.8.193:8081; object-src &apos;self&apos; data: http://127.0.0.1:8081 http://192.168.8.193:8081; style-src &apos;self&apos; &apos;unsafe-inline&apos; data: ; img-src *; media-src &apos;self&apos; data: http://127.0.0.1:8081 http://192.168.8.193:8081; frame-src &apos;self&apos; data: http://127.0.0.1:8081 http://192.168.8.193:8081; font-src *; connect-src &apos;self&apos; data: http://127.0.0.1:8081 http://192.168.8.193:8081">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <title>Device Router</title>

    <style>
        html {
            background: #DDD;
            font-size: 14px;
            color: #222;
            font-family: Arial, sans-serif;
        }

        html, body {
            padding: 0;
            margin: 0;
        }

        html * {
            box-sizing: border-box;
        }

        #unavailable {
            display: block;
        }

        #unavailable p {
            display: none;
            font-size: 15px;
            background: #444;
            color: #FFF;
            padding: 20px;
            margin: 10px;
            border-radius: 10px;
            line-height: 24px;
        }

        #status_text {
            display: block;

            background: #2196F3;
            color: #FFF;
            padding: 20px;
            margin: 10px;

            -webkit-border-radius: 10px;
            -moz-border-radius: 10px;
            border-radius: 10px;
        }

        input {
            display: block;
            background: #FFF;
            border: 1px solid #CCCCCC;
            font-size: 14px;
            color: #222;
            width: 100%;
            height: 46px;
            padding: 10px;
        }

        button {
            display: block;
            margin-top: 10px;
            width: 100%;
            height: 34px;
        }

        .input_wrap {
            padding: 0 10px;
        }
    </style>

</head>
<body><script>const localServerIp = '192.168.8.193'</script>

    <div id="unavailable">
        <p>
            It seems we can&apos;t connect to<br>127.0.0.1:8081<br>
            <script>document.write(localServerIp)</script>
            :8081<br><br>
            You can test yourself with next inputs:
        </p>

        <div id="status_text">
            Waiting for device ready...
        </div>

        <div class="input_wrap">
            <input type="text" placeholder="Server Ip:Port (like 192.168.0.2:8081)" disabled>
        </div>

        <div class="input_wrap">
            <button type="button" onclick="tryConnect()" disabled>Connect</button>
        </div>
    </div>

    <script>
        var deviceReadyChecker = setTimeout(startRedirectChecks, 5000);

        document.addEventListener("deviceready", function () {
            clearTimeout(deviceReadyChecker);

            if (typeof navigator.splashscreen !== "undefined" && typeof navigator.splashscreen.hide === "function")
                navigator.splashscreen.hide();

            startRedirectChecks();
        });

        function startRedirectChecks() {
            testConnection('127.0.0.1:8081', goUrl, function () {
                testConnection(localServerIp + ':8081', goUrl, ajaxErr)
            })
        }

        function tryConnect() {
            var ipTest = /^([0-9]{1,3}\.){3}[0-9]{1,3}(:[0-9]{1,6})?$/,
            ipPort = document.querySelector("input").value;

            if (ipTest.test(ipPort))
                testConnection(ipPort, goUrl, ajaxErr);
        }

        function testConnection(ipPort, callback, errCallback) {
            var xhr = new XMLHttpRequest();

            document.querySelector("button").disabled = true;
            document.querySelector("input").disabled = true;
            document.querySelector("#status_text").innerText = "Trying to connect http://" + ipPort;

            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    document.querySelector("#status_text").innerText = "Connection to 'http://" + ipPort + "/' success! Redirecting...";

                    if (typeof callback === "function")
                        callback(ipPort);
                }
                else if (xhr.readyState === 4 && xhr.status !== 200) {
                    document.querySelector("button").disabled = false;
                    document.querySelector("input").disabled = false;
                    document.querySelector("#status_text").innerText = "Connection to 'http://" + ipPort + "/' failed!";

                    if (typeof errCallback === "function")
                        errCallback(ipPort);
                }
            }

            xhr.open('GET', 'http://' + ipPort + '/');
            xhr.send(null);
        }

        function goUrl(ipPort) {
            setTimeout(function () {
                window.location.href = 'http://' + ipPort + '/'
            }, 1500);
        }

        function ajaxErr(ipPort) {
            document.querySelector("#unavailable p").style.display = "block";
            console.log('Can\'t connect to http://' + ipPort + '/');
        }

    </script>


    <script src="cordova.js"></script></body></html>

0 个答案:

没有答案