2015年5月1日 星期五

如何設定Codova 呼叫WEB API

  一般在asp.net的網站呼叫WEB API是很簡單,但如果透過Codova 呼叫WEB API,有很多小地方需要注意,畢竟它可不是一般網頁這麼簡單,作者已經用node.js WEB API,打算用VS Codova 的專案,呼叫Node.jsWEB API,並顯示在手持裝置上。

一、node.js 架的WEB API伺服器

var express = require('express');
var app = express();
app.get('/patients', function (req, res) {
//允許跨源處理的協定
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');

//呼叫mongoDB 資料表
    var mongo = require('mongodb');
    var Server = mongo.Server;
    var Db = mongo.Db;
    var server = new Server('192.168.1.63', 27017, { auto_reconnect: true });
//呼叫 cooper 資料庫
    var db = new Db('cooper', server);
    db.open(function () {
//呼叫 patient 集合,在mongodb中並無資料表名稱,而是以集合,因為儲存架構key,value
        db.collection('patient', function (err, collection) {
            collection.find().toArray(function (err, items) {                               
                res.send(items);
            });
        });
    });
});
app.listen(3000);
console.log('Listening on port 3000...');

如果對node.js 的篇幅有興趣的朋友,可以順便看『node.js 初體驗』的文章

二、Codova 呼叫WEB API

可以用喜歡的框架(jqueryMobile metro)等相關套件,引入相關的JavaScript
<meta name="viewport" content="width=device-width, initial-scale=1" charset="utf-8">
<link href="css/metro-bootstrap.min.css" rel="stylesheet" />
<script src="js/jquery/jquery-2.1.3.min.js"></script>
<script src="js/jquery/jquery-ui.min.js"></script>
<script src="js/metro.min.js"></script>
<script src="js/metro/metro-dropdown.js"></script>
<link href="css/index.css" rel="stylesheet" />

主程式
<body class="metro" data-ng-app="patientModule">
    <div class="panel">
        <div class="panel-header bg-lightBlue fg-white">
            病患列表
            <div class="button-dropdown" id="menu">
                <button class="dropdown-toggle primary large">選單</button>
                <ul class="dropdown-menu" data-role="dropdown">
                    <li><a href="camera.html">拍照</a></li>
                    <li><a href="accelerometer.html">加速感測</a></li>
                    <li><a href="signalR.html">線上聊天</a></li>
                    <li class="divider"></li>
                    <li><a href="touch.html">推播</a></li>
                    <li><a href="sample.html">小遊戲</a></li>
                </ul>
            </div>
        </div>
        <div class="panel-content">
            <div ng-controller="patientController">               
                <div class="input-control text">
                    <input type="text" placeholder="請輸入病患姓名" ng-model="searchText" />
                    <button class="btn-search"></button>
                </div>
                <div class="listview" ng:repeat="person in patients| filter:searchText">
                    <a href="detail.html?id={{person.Name}}" class="list">
                        <div class="list-content">
                            <img src="images/boy.jpg" class="icon" ng-if="person.Sex==1" />
                            <img src="images/girl.jpg" class="icon" ng-if="person.Sex==0" />
                            <div class="data">
                                <span class="list-title">{{person.Name}}</span>
                                <span class="list-remark">最後就診日: {{person.LastViewClinic}}</span>
                            </div>
                        </div>
                    </a>
                </div>
            </div>
        </div>
    </div>
    <script src="cordova.js"></script>
    <script src="scripts/platformOverrides.js"></script>   
    <script src="scripts/angular.min.js"></script>
    <script>
    (function () {
        "use strict";
        var app = angular.module("patientModule", []);
        //允許codova 跨源的設定;
        app.config(['$httpProvider', function ($httpProvider) {
            $httpProvider.defaults.useXDomain = true;
            delete $httpProvider.defaults.headers.common['X-Requested-With'];
        }]);
        var patients = [];
        app.controller("patientController", function ($scope, $timeout, $window, $http) {
//呼叫WEB API           
            $http.get("http://192.168.1.63:3000/patients").success(function (data, status, header, config) {
                for (var i = 0; i <= data.length - 1; i++) {
                    patients.push({
                        Name: data[i].病患姓名,
                        Id: data[i].ikey,
                        Sex: ((data[i].性別 == "") ? 1 : 0),
                        LastViewClinic: data[i].上次就診日,
                    });
                }             
            }).error(function (data, status, headers, config) {
                alert("web api 網址失敗!");
            })
//值傳遞到網頁上
            $scope.patients = patients;
            $scope.go = function (path) {
                $window.location.href = path;
            };
        });
    })();
    </script>
</body>

   
三、在專案路徑下à找尋config.xml 點選二下


















Codova 如果要呼叫外部的網址,需要在Domain Access 輸入Web API網址,否則會被擋掉。

















成功可以從手機上直接呼叫WEB API

        

感謝各位的參訪, 如果有任何錯誤的地方,請高手指點囉!













沒有留言:

張貼留言