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

「这是我参与2022首次更文挑战的第33天,活动详情查看:2022首次更文挑战

错误消息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 标签页里能看到:

解决方案:

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://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);
复制代码

猜你喜欢

转载自juejin.im/post/7066253644651298824