UI5使用Post方式发送Json文件到Odata

本文介绍了解决UI5应用在向Odata发送Json数据时遇到403错误的方法。通过先使用GET请求获取Token,再在POST请求中携带该Token,成功解决了权限问题。

最近遇到一个需求,通过BTP上开发一个UI5应用。该应用需要将Json数据发送到Odata。

在使用post发送数据过程中,遇到了403错误。

最后发现是缺少Token。所以,先使用Get方法获取Token给到POST。

再在POST中使用该Token,最终解决了此错误。

下面是App参考代码

View文件

<mvc:View controllerName="zpoptest02.zpoptest02.controller.View1"
	xmlns:l="sap.ui.layout"
    xmlns:mvc="sap.ui.core.mvc" displayBlock="true"
    xmlns="sap.m">
	<l:VerticalLayout id="viewpage" class="sapUiContentPadding" width="100%">
      <Input
        id="zIFID"
        description="IFID"
        value="FORM_TEST001"
        valueLiveUpdate="true"
        width="20%"/>
      <Input
        id="zSYSID"
        description="SYSID"
        value="FRM"
        valueLiveUpdate="true"
        width="20%"/>
     <Input
        id="VKORG"
        description="销售组织"
        value="1000"
        valueLiveUpdate="true"
        width="20%"/>
     <Input
        id="WERKS_L"
        description="工厂-low"
        value="0001"
        valueLiveUpdate="true"
        width="20%"/>
     <Input
        id="WERKS_h"
        description="工厂-high"
        value="1000"
        valueLiveUpdate="true"
        width="20%"/>
		<Button
            id="mybutton2"
			text="执行"
			width="230px"
			press=".onlinkpress"
			class="sapUiSmallMarginBottom"
			ariaHasPopup="Dialog" />
	</l:VerticalLayout>
</mvc:View>

 Fragment文件

<core:FragmentDefinition
   xmlns="sap.m"
   xmlns:core="sap.ui.core" >
   <Dialog
      id="helloDialog" title="Link list" contentWidth="550px" contentHeight="300px" resizable="true">
      <beginButton>
         <Button
            text="{i18n>dialogCloseButtonText}"
            press=".onCloseDialog"/>
      </beginButton>

    <Table noDataText="No data to display"
                items="{/d/results}" id="table0">
    <items>
            <ColumnListItem type="Active" id="item0">
        <cells>
        <Text text="{field1}" id="text0"/>
        <Text text="{field2}" id="text1"/>
        <!-- <Link id="Test" text="{field2}" href="{field2}"></Link> -->
        </cells>
        </ColumnListItem>
    </items>
    <columns>
        <Column id="column0">
        <header>
        <Label text="列2" id="label0"/>
        </header>
        </Column>
        <Column id="column1">
        <header>
        <Label text="列1" id="label1"/>
        </header>
        </Column>
     </columns>
     </Table>
   </Dialog>
</core:FragmentDefinition>

js文件

在使用POST发送Json文件时,遇到了403错误。需要添加GET方法获取Token

 js完整代码如下:

sap.ui.define([
        "sap/ui/core/mvc/Controller",
        "sap/ui/model/json/JSONModel",
        "sap/ui/core/IconPool",
        "sap/m/Dialog",
        "sap/m/Button",
        "sap/m/library",
        "sap/m/List",
        "sap/m/StandardListItem",
        "sap/m/DisplayListItem",
        "sap/m/Text",
    ],function (Controller, JSONModel, IconPool, Dialog, Button, mobileLibrary, List, StandardListItem, DisplayListItem,Text) {
            "use strict";
        // shortcut for sap.m.ButtonType
            var ButtonType = mobileLibrary.ButtonType;
    
                // shortcut for sap.m.DialogType
            var DialogType = mobileLibrary.DialogType;
    
            return Controller.extend("zpoptest02.zpoptest02.controller.View1", {

                // url link get
                onlinkpress: function (oEvent) { 
                // get ui field value
                    var zIFID = this.getView().byId("zIFID").getValue();
                    var zSYSID = this.getView().byId("zSYSID").getValue();
                    var VKORG = this.getView().byId("VKORG").getValue();
                    var WERKS_L = this.getView().byId("WERKS_L").getValue();
                    var WERKS_h = this.getView().byId("WERKS_h").getValue();    
                    console.log("zIFID===",zIFID);
                    console.log("zSYSID====",zSYSID);
                    console.log("VKORG====",VKORG);
                    console.log("WERKS_L====",WERKS_L);    
                    console.log("WERKS_h====",WERKS_h);      
                //start
                var token = null;
                jQuery.ajax({
                    url: url,
                    type: "GET",
                    async: false,
                    beforeSend: function(xhr) {
                        xhr.setRequestHeader("X-CSRF-Token", "Fetch");
                    },
                    complete: function(xhr) {
                        token = xhr.getResponseHeader("X-CSRF-Token");
                    }

                });
                console.log("token===",token)

                // post Json
                //这里根据自己实际情况设定Json文件
                var bodydata={
                "field1": field3,
                "field2": field2,
                "field3": field1,
                };

                console.log("bodydata==",bodydata)

                var oModel = new sap.ui.model.json.JSONModel();
                var that = this;
                var aData2 = jQuery.ajax({   
                type: "POST",                    
                contentType: "application/json",
                url: url  //odata url                   
                dataType: "json",
                headers: {
                    'Accept': 'application/json',
                    'X-CSRF-Token':token,  // get方法取得的Token  
                },
                data:JSON.stringify(bodydata),
                async: false,
                success: function(data, textStatus, jqXHR) {
                oModel.setData(data);
                alert("success to post");
                }
                });
                this.getView().setModel(oModel);
                console.log("oDATA2==",aData2)
                //end     
                                    // create dialog lazily
                                if (!this.pDialog) {
                                    this.pDialog = this.loadFragment({
                                        name: "zpoptest02.zpoptest02.view.linkDialog"
                                    });
                                } 
                                this.pDialog.then(function(oDialog) {
                                    oDialog.open();
                                });            
                                },

                                onCloseDialog : function () {
                                    this.byId("helloDialog").close();
                                }
                                
            });
        });

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值