cancel
Showing results for 
Search instead for 
Did you mean: 

401 unauthorized error when trying to make a POST and already logged into the database

csimpson
Explorer
0 Kudos

As the title says I get a 401 unauthorized error when trying to make a POST and already logged into the database through the service layer. I can do updates and get requests fine. Cors is all set up fine as well.

sap.ui.define([
    "./BaseController",
    "sap/ui/model/json/JSONModel",
    "sap/ui/core/routing/History",
    "../model/formatter"
], function (BaseController, JSONModel, History, formatter) {
    "use strict";

    return BaseController.extend("ECSB1.VendorPriceChangesV2.controller.Object", {

        formatter: formatter,

        /* =========================================================== */
        /* lifecycle methods                                           */
        /* =========================================================== */

        /**
         * Called when the worklist controller is instantiated.
         * @public
         */
        onInit : function () {
            // Model used to manipulate control states. The chosen values make sure,
            // detail page is busy indication immediately so there is no break in
            // between the busy indication for loading the view's meta data
            var iOriginalBusyDelay,
                oViewModel = new JSONModel({
                    busy : true,
                    delay : 0
                });

            this.getRouter().getRoute("object").attachPatternMatched(this._onObjectMatched, this);

            // Store original busy indicator delay, so it can be restored later on
            iOriginalBusyDelay = this.getView().getBusyIndicatorDelay();
            this.setModel(oViewModel, "objectView");
            this.getOwnerComponent().getModel().metadataLoaded().then(function () {
                    // Restore original busy indicator delay for the object view
                    oViewModel.setProperty("/delay", iOriginalBusyDelay);
                }
            );
            //Loging into the database
            var user = "user";
            var pass = "password";
            var comp = "company";
            var jData = JSON.stringify({
                UserName: user,
                Password: pass,
                CompanyDB: comp
            });
            
            var sysID = "https://company.com:50000";
            var loginURL = sysID + "/b1s/v1/Login";
            
            $.ajax({
                url: loginURL,
                xhrFields: {
                    withCredentials: true
                },
                data: jData,
                type: "POST",
                dataType: "json",
                success: function (result) {
                    if (result.error) {
                        //alert(result.error);
                        console.log("Edit - success error");
                        return;
                    } else {
                        console.log("Edit - success - logged in");
                    }
                },
                error: function (request, textStatus, errorThrown) {
                    //alert("Service Layer Login failed: " + textStatus + " / " + errorThrown );
                    console.log("Edit - error");
                }
            });
        },

        /* =========================================================== */
        /* event handlers                                              */
        /* =========================================================== */


        /**
         * Event handler  for navigating back.
         * It there is a history entry we go one step back in the browser history
         * If not, it will replace the current entry of the browser history with the worklist route.
         * @public
         */
        onNavBack : function() {
            var sPreviousHash = History.getInstance().getPreviousHash();

            if (sPreviousHash !== undefined) {
                history.go(-1);
            } else {
                this.getRouter().navTo("worklist", {}, true);
            }
        },

        /* =========================================================== */
        /* internal methods                                            */
        /* =========================================================== */

        /**
         * Binds the view to the object path.
         * @function
         * @param {sap.ui.base.Event} oEvent pattern match event in route 'object'
         * @private
         */
        _onObjectMatched : function (oEvent) {
            var sObjectId =  oEvent.getParameter("arguments").objectId;
            this.getModel().metadataLoaded().then( function() {
                var sObjectPath = this.getModel().createKey("PrcVndWrkView", {
                    Code :  sObjectId
                });
                this._bindView("/" + sObjectPath);
            }.bind(this));
        },

        /**
         * Binds the view to the object path.
         * @function
         * @param {string} sObjectPath path to the object to be bound
         * @private
         */
        _bindView : function (sObjectPath) {
            var oViewModel = this.getModel("objectView"),
                oDataModel = this.getModel();

            this.getView().bindElement({
                path: sObjectPath,
                events: {
                    change: this._onBindingChange.bind(this),
                    dataRequested: function () {
                        oDataModel.metadataLoaded().then(function () {
                            // Busy indicator on view should only be set if metadata is loaded,
                            // otherwise there may be two busy indications next to each other on the
                            // screen. This happens because route matched handler already calls '_bindView'
                            // while metadata is loaded.
                            oViewModel.setProperty("/busy", true);
                        });
                    },
                    dataReceived: function () {
                        oViewModel.setProperty("/busy", false);
                    }
                }
            });
        },

        _onBindingChange : function () {
            var oView = this.getView(),
                oViewModel = this.getModel("objectView"),
                oElementBinding = oView.getElementBinding();

            // No data for the binding
            if (!oElementBinding.getBoundContext()) {
                this.getRouter().getTargets().display("objectNotFound");
                return;
            }

            var oResourceBundle = this.getResourceBundle(),
                oObject = oView.getBindingContext().getObject(),
                sObjectId = oObject.Code,
                sObjectName = oObject.Code;

            oViewModel.setProperty("/busy", false);

            oViewModel.setProperty("/shareSendEmailSubject",
            oResourceBundle.getText("shareSendEmailObjectSubject", [sObjectId]));
            oViewModel.setProperty("/shareSendEmailMessage",
            oResourceBundle.getText("shareSendEmailObjectMessage", [sObjectName, sObjectId, location.href]));
        },
        
        onSave: function(){
            //var yes = "Y";
            //var no = "N";
            var url = "https://company:50000/b1s/v1/";
            var code = this.getView().byId("idCode").getValue();
            
            var updateURL = url + "ECSB1_VNDPRICECHG" + "('" + code +"')";
            var uApproved = this.getView().byId("idApprove").getValue();
            uApproved = uApproved.toUpperCase(); //Converts anything typed to uppercase.
            
            /*if(uApproved !== yes || uApproved !== no){
                alert("Please enter Y or N");
            }*/
            
            console.log(uApproved);
            

            var data = JSON.stringify({
                "U_Approved": uApproved
            });
            
            console.log(updateURL);
            
            $.ajax({
                    url: updateURL,
                    data: data,
                    type:"PATCH",
                    xhrFields: {
                        withCredentials: true
                    },
                    dataType:"json",
                    error: function (request, textStatus, errorThrown) {
                        //alert("Service Layer Login failed: " + textStatus + " / " + errorThrown );
                        alert("Please enter Y or N");
                    }
                    
                    
            });
            var sPreviousHash = History.getInstance().getPreviousHash();
            if (sPreviousHash !== undefined) {
                history.go(-1);
            } else {
                this.getRouter().navTo("worklist", {}, true).reload();
            }
                
            
        
            //console.log(uApproved);
        }

    });

});


Accepted Solutions (0)

Answers (0)