使用 SAP UI5 消费 OData 服务的一些常见错误和解决方案
錯誤消息1
Access to XMLHttpRequest at ‘http://localhost:8081/https://services.odata.org/V2/Northwind/Northwind.svc/$metadata?sap-language=EN’ from origin ‘http://localhost:8080’ has been blocked by CORS policy: Request header field maxdataserviceversion is not allowed by Access-Control-Allow-Headers in preflight response.
原因是 maxdataserviceversion 這個和 OData 服務版本相關的字段,沒有出現在服務器端配置的 Access-Control-Allow-Headers 數組里,因此引起了跨域 CORS error.
maxdataserviceversion 這個字段在 Chrome 開發者工具 network 標簽頁里能看到:
解決方案:
將 Access-Control-Allow-Headers 的值改成 * 即可。錯誤消失:
錯誤2
下面 url 對應的 metadata,無法在瀏覽器里正常顯示。期望的結果是,地址欄里輸入 url 之后,我們能看到 http://localhost:8081/ 后面的 metadata 實際的內容,以 xml 格式正常顯示:
http://localhost:8081/https://services.odata.org/V2/Northwind/Northwind.svc/$metadata?sap-language=EN
正常情況下,請求的 header 字段是:
Accept: application/xml
根據 express response 對象的 API 說明,如果 send 方法傳入的參數是一個字符串,則響應結構的 Content-Type 自動設置為text/html:
這一點可以在 Postman 里觀察到:
我們可以在代理服務器的實現里,使用 res.set 方法可以將 Content-Type 手動修改成 application/xml:
這樣,在瀏覽器里就能正常顯示, 通過代理服務器獲取的 xml 格式的 metadata 了:
錯誤消息3
The /$batch resource only supports POST method request
header 字段里包含了 boundary 值:
對于 $batch 操作來說,Accept 的值為 multipart/mixed:
確實就掛起了:
當消費者想要執行多個獨立的 HTTP 調用并希望避免多次服務器往返時,通常會使用 OData 批處理請求。
在 SAP UI5 里使用 OData Model 發送 batch 請求的示例代碼如下:
var tmpModel = new ODataModel("https://xxyyzz.com/sap/opu/odata/<your_service>_SRV/", true); tmpModel.setDefaultBindingMode(sap.ui.model.BindingMode.TwoWay); tmpModel.setUseBatch(true); this.getView().setModel(tmpModel, "tmpModel"); tmpModel.setDeferredGroups(["foo"]); var mParameters = {groupId:"foo",success:function(odata, resp){ console.log(resp); },error: function(odata, resp) { console.log(resp); }};for(var m=0; m<oPayload.length; m++) {tmpModel.update("/YOUR_ENTITYSet(Key1='Valu1',Key2='Value2')", oPayload[m], mParameters); } tmpModel.submitChanges(mParameters);更多Jerry的原創文章,盡在:“汪子熙”:
總結
以上是生活随笔為你收集整理的使用 SAP UI5 消费 OData 服务的一些常见错误和解决方案的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 以下哪个物种是我国所独有的?蚂蚁庄园5.
- 下一篇: 轻办公体验再升级!华为官宣新系列平板 补