关于javascript:使用-SAP-UI5-消费-OData-服务的一些常见错误和解决方案

6次阅读

共计 1872 个字符,预计需要花费 5 分钟才能阅读完成。

谬误音讯 1

Access to XMLHttpRequest at ‘http://localhost:8081/https:/…$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 标签页里能看到:

解决方案:

app.all('*', function(req, res, next) {res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "*");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",'9.0.0');
    next();});

Access-Control-Allow-Headers 的值改成 * 即可。谬误隐没:

谬误 2

上面 url 对应的 metadata,无奈在浏览器里失常显示。冀望的后果是,地址栏里输出 url 之后,咱们能看到 http://localhost:8081/ 前面的 metadata 理论的内容,以 xml 格局失常显示:

http://localhost:8081/https:/…$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 的原创文章,尽在:” 汪子熙 ”:

正文完
 0