UI5 Mock Server with Local Data: “rootUri” Not Working

為{幸葍}努か 提交于 2019-12-31 04:02:57

问题


I'm currently following the UI5 tutorial and am stuck on step 27: Mock Server Configuration.

The problem is the rootUri configuration of the mock server. I am using the Northwind OData service as per tutorial and have configured a dataSource for Invoices in the manifest.json.

Now, to use the local mock data instead of the online service, I created the necessary files as stated by the tutorial. When I then run the mockServer.html, the server doesn't redirect the service request to the local mock data, but instead makes the request and fails because of web security issues.

If I use the following rootUri, the mock server doesn't redirect and the service request fails:

// Snippet from mockserver.js
var oMockServer = new MockServer({
    rootUri: "/destinations/northwind/V2/Northwind/Northwind.svc/"
});

Failed to load https://services.odata.org/V2/Northwind/Northwind.svc/$metadata?sap-language=DE: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://webidetesting9515320-s0015250556trial.dispatcher.hanatrial.ondemand.com' is therefore not allowed access. The response had HTTP status code 501.

Another question on Stackoverflow shows the mock server using a "wildcard" root-uri, but this also fails:

// Snippet from mockserver.js
var oMockServer = new MockServer({
    rootUri: "/"
});

The only way I can make the mock server configuration work is to use the exact same URL as the rootUri that is written in the manifest.json as the URI of the dataSource I want to mock:

// Snippet from mockserver.js
var oMockServer = new MockServer({
    rootUri: "https://services.odata.org/V2/Northwind/Northwind.svc/"
});

The above code works, but the Web IDE states that this is a bad practice:

error: Fiori Architectural Guidelines: ESLint(sap-no-hardcoded-url): Hardcoded (non relative) URL found. (img)

My question now is: How can I make the mock server run the intended way with a relative rootUri?


webapp/manifest.json (excerpt)

{
  "_version": "1.1.0",
  "sap.app": {
    "_version": "1.1.0",
    "id": "sap.ui.tutorial.walkthrough",
    "type": "application",
    "i18n": "i18n/i18n.properties",
    "title": "{{appTitle}}",
    "description": "{{appDescription}}",
    "applicationVersion": {
      "version": "1.0.0"
    },
    "dataSources": {
      "invoiceRemote": {
        "uri": "https://services.odata.org/V2/Northwind/Northwind.svc/",
        "type": "OData",
        "settings": {
          "odataVersion": "2.0"
        }
      }
    }
  },
...

webapp/test/mockServer.html

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta charset="utf-8">
        <title>Hello World App - Test Page</title>
        <script src="/resources/sap-ui-core.js"
                id="sap-ui-bootstrap"
                data-sap-ui-theme="sap_belize"
                data-sap-ui-libs="sap.m"
                data-sap-ui-compatVersion="edge"
                data-sap-ui-preload="async"
                data-sap-ui-resourceroots='{
                    "sap.ui.tutorial.walkthrough": "../"
                }'></script>

        <script type="text/javascript">
            sap.ui.getCore().attachInit(function() {
                sap.ui.require([
                    "sap/ui/tutorial/walkthrough/localService/mockserver",
                    "sap/m/Shell",
                    "sap/ui/core/ComponentContainer"
                ], function(mockserver, Shell, ComponentContainer) {
                    mockserver.init();

                    new Shell({
                        app: new ComponentContainer({
                            name: "sap.ui.tutorial.walkthrough",
                            height: "100%"
                        })
                    }).placeAt("content")
                });
            });
        </script>
    </head>
    <body class="sapUiBody" id="content">
    </body>
</html>

webapp/localService/mockserver.js

sap.ui.define([
    "sap/ui/core/util/MockServer"
], function (MockServer) {
    "use strict";

    return {
        init: function () {
            // create
            var oMockServer = new MockServer({
                rootUri: "https://services.odata.org/V2/Northwind/Northwind.svc/"
            });
            var oUriParameters = jQuery.sap.getUriParameters();
            // configure
            MockServer.config({
                autoRespond: true,
                autoRespondAfter: oUriParameters.get("serverDelay") || 1000
            });
            // simulate
            var sPath = jQuery.sap.getModulePath("sap.ui.tutorial.walkthrough.localService");
            oMockServer.simulate(sPath + "/metadata.xml", sPath + "/mockdata");
            // start
            oMockServer.start();
        }
    };
});

webapp/localService/metadata.xml

<edmx:Edmx Version="1.0" xmlns:edmx="http://schemas.microsoft.com/ado/2007/06/edmx">
    <edmx:DataServices m:DataServiceVersion="1.0" m:MaxDataServiceVersion="3.0"
                       xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata">
        <Schema Namespace="NorthwindModel" xmlns="http://schemas.microsoft.com/ado/2008/09/edm">
            <EntityType Name="Invoice">
                <Key>
                    <PropertyRef Name="ProductName"/>
                    <PropertyRef Name="Quantity"/>
                    <PropertyRef Name="ShipperName"/>
                </Key>
                <Property Name="ShipperName" Type="Edm.String" Nullable="false" MaxLength="40" FixedLength="false"
                          Unicode="true"/>
                <Property Name="ProductName" Type="Edm.String" Nullable="false" MaxLength="40" FixedLength="false"
                          Unicode="true"/>
                <Property Name="Quantity" Type="Edm.Int16" Nullable="false"/>
                <Property Name="ExtendedPrice" Type="Edm.Decimal" Precision="19" Scale="4"/>
            </EntityType>
        </Schema>
        <Schema Namespace="ODataWebV2.Northwind.Model" xmlns="http://schemas.microsoft.com/ado/2008/09/edm">
            <EntityContainer Name="NorthwindEntities" m:IsDefaultEntityContainer="true" p6:LazyLoadingEnabled="true"
                             xmlns:p6="http://schemas.microsoft.com/ado/2009/02/edm/annotation">
                <EntitySet Name="Invoices" EntityType="NorthwindModel.Invoice"/>
            </EntityContainer>
        </Schema>
    </edmx:DataServices>
</edmx:Edmx>

回答1:


There are some rules to watch out for when it comes to defining the rootUri for mock server.

The rootUri

  • Should be relative
  • Has to end with a slash ("/")
  • Has to match with the URI that is assigned to your model.

It is mentioned in the step 27:

(The rootUri) matches the URL of our data source in the descriptor file.

As well as in the topic Mock Server: Frequently Asked Questions:

The root URI has to be relative and requires a trailing '/'. It also needs to match the URI set in OData/JSON models or simple XHR calls in order for the mock server to intercept them.


So it doesn't matter how your rootUri is defined as long as it fulfills those three requirements mentioned above. That's why some arbitrary URIs like rootUri: "/" works as well but only if the uri in the dataSource is the same.

In your case, changing the rootUri value like this below should make the mock server running:

var oMockServer = new MockServer({
  rootUri: "/destinations/northwind/V2/Northwind/Northwind.svc/"
});

And in your app descriptor (manifest.json) respectively..:

"dataSources": {
  "invoiceRemote": {
    "uri": "/destinations/northwind/V2/Northwind/Northwind.svc/",
    "type": "OData",
    "settings": {
      "odataVersion": "2.0"
    }
  }
}

To make the path work in a non-MockServer scenario, you'll need to register a corresponding destination in SAP Cloud Platform and edit neo-app.json in your project accordingly.
No need to change the application code.




回答2:


Some details of chapter 27 of the tutorial are quite misleading.

  1. The rootUri of the MockServer must match the uri parameter of the datasource in manifest.json.

  2. Instead of changing datasource's uri to the (wrong) rootUri of MockServer given in the tutorial, you should actually change MockServer's rootUri to the URI of the external source. In webapp/localService/mockserver.js use this corrected block:

        var oMockServer = new MockServer({
            rootUri: "https://services.odata.org/V2/Northwind/Northwind.svc/"
        });
    

This will create a MockServer that intercepts all calls to that external URI and responds to them locally. And with this construct, it is actually possible to access the MockServer through /webapp/test/mockServer.html and the live data server through /webapp/index.html.

Hint:
You will most likely still have trouble accessing the original (external) data source using /webapp/index.html due to Same Origin Policy restrictions (SOP). With Google Chrome this can be nicely solved by running a second (!) instance of the browser without SOP. This is possible in parallel to other open browser windows of the standard instance WITH SOP, so you don't need to close all your open browser windows. See this answer for details.



来源:https://stackoverflow.com/questions/46664672/ui5-mock-server-with-local-data-rooturi-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!