1

Ok, this is my first time to post here so if you see that I need to correct something please tell me.

I'm having problem when I try to post data to an api using ajax. I am using tomcat8 as my web server. I added the @CrossOrigin annotation in my controller which were suggested by others. I also added the localhost:9000 as allowed-origin and Authorization in allowed-headers in my servlet.xml but still no success.

This is my ajax code:

var my_url = "http://localhost:8088/booking/api/saveTransaction";
var username = "user111";
var password = "userpass111";

              $.ajax({
                  method: "POST",
                  url: my_url,
                  dataType: "json",
                  headers: {
                    'Authorization':'Basic ' + btoa(username+":"+password),
                    'Content-Type':'x-www-form-urlencoded'
                  },
                  data: JSON.stringify(my_data),
                  success: function(data){
                    alert(data);
                  },
                  error: function(xhr, status, error){
                    alert(xhr);
                    alert(status);
                    alert(error);
                  }
              });

In my Controller

@CrossOrigin(origins = "http://localhost:9000")
@RequestMapping(value = "/api/saveTransaction", method = RequestMethod.POST)
public ResponseEntity<BiyaheApplicationResult> saveTransaction(Authentication authentication, @RequestBody CompanyTransaction transaction) {

    System.out.println("\n\n");
    System.out.println("START-SAVE-TRANSACTION");
    System.out.println("\n\n");

    BiyaheApplicationResult result = null;

    if(null != transaction) transaction.setTransactionDate(new Date());

    System.out.println("\n\n");
    System.out.println("TEST: SAVE-JSON-TRANSACTION");
    System.out.println("--------------------------------------------");
    System.out.println("[transaction]: " + BiyaheTextFormatter.serializeToJson(transaction));
    System.out.println("--------------------------------------------");
    System.out.println("\n\n");

    String username = authentication.getName();
    User user = this.userService.findUserByUsername(username);
    UserProfileView profile = this.userProfileViewService.getUserProfileViewById(user.getId());

    int companyId = -1;
    int branchId = -1;
    String loadingScheme = null;
    if(null != profile){
        if(BiyaheConstants.JGGC_HQ_COMPANY_ID < profile.getCompanyId()){
            companyId = profile.getCompanyId();
            CompanyConfiguration conf = this.companyConfigurationService.getCompanyConfigurationByCompanyId(companyId);
            loadingScheme = conf.getLoadingScheme();
        }

        if(BiyaheConstants.JGGC_HQ_BRANCH_ID < profile.getBranchId()){
            branchId = profile.getBranchId();
        }
    }

    double currentLoad = 0;

    boolean isSufficientLoad = false;
    if(BiyaheConstants.LOADING_SCHEME_CENTRALIZED.equalsIgnoreCase(loadingScheme)){
        CompanyLoadInfo coLoadInfo = this.companyLoadInfoService.getCompanyLoadInfoByCompanyId(companyId);
        if(null != coLoadInfo) {
            currentLoad = coLoadInfo.getCentralizeLoadAmount();
            isSufficientLoad = coLoadInfo.getCentralizeLoadAmount() > transaction.getTotalAmount();
        }
    }
    else if(BiyaheConstants.LOADING_SCHEME_DISTRIBUTED.equalsIgnoreCase(loadingScheme)){
        BranchLoadInfo branchLoadInfo = this.branchLoadInfoService.getBranchLoadInfoByBranchId(branchId);
        if(null != branchLoadInfo) {
            currentLoad = branchLoadInfo.getBranchLoad();
            isSufficientLoad = branchLoadInfo.getBranchLoad() > transaction.getTotalAmount();
        }
    }

    System.out.println("\n\n");
    System.out.println("SAVE-TRANSACTION");
    System.out.println("--------------------------------------------");
    System.out.println("[username]: " + username);
    System.out.println("[company]: " + profile.getCompanyName());
    System.out.println("[branch]: " + profile.getBranchName());
    System.out.println("[loading-scheme]: " + loadingScheme);
    System.out.println("[current-load-balance]: " + currentLoad);
    System.out.println("[transactionAmount]: " + transaction.getTotalAmount());
    System.out.println("[itemPrice]: " + transaction.getItemPriceTotal());
    System.out.println("[totalMarkup]: " + transaction.getMarkUpTotal());
    System.out.println("[isSufficientLoad]: " + isSufficientLoad);
    System.out.println("--------------------------------------------");
    System.out.println("\n\n");

    if(isSufficientLoad){
        /*
        {
            "transactionDate":null,
            "transactionType":"HOTEL",
            "transactionCode":"SOGO-6969",
            "totalAmount":2500.0,
            "itemPriceTotal":2250.0,
            "markUpTotal":250.0,
            "quantity":1.0,
            "customerName":"Rowena Palami",
            "customerEmail":"weng.palami@gmail.com",
            "customerContact":"(0918) 222-6969",
            "customerAddress":"Room #69 SOGO Hotel, Guadalupe, EDSA, MM"
        }
        * */

        String generatedReservationCode = null;
        do {
            generatedReservationCode = this.biyaheTransactionService.generateTransactionCode(10);
        }
        while(this.biyaheFlightSalesService.checkReservationCodes(generatedReservationCode));

        BiyaheSales sale = transaction.toBiyaheSales();
        sale.setReservationCode(generatedReservationCode);

        sale.setTransactionDate(new Date());
        sale.setAgent(user);

        System.out.println("\n\n");
        System.out.println("API :: SAVE-TRANSACTION");
        System.out.println("------------------------------------------------");
        System.out.println(sale.toString());
        System.out.println("------------------------------------------------");
        System.out.println("\n\n");

        this.biyaheFlightSalesService.addUpdateBiyaheFlightSales(sale);

        result = new BiyaheApplicationResult(SUCCESS_CODE_TRANSACTION_SAVE, SUCCESS_DISPLAY_TRANSACTION_SAVE);
        return new ResponseEntity(BiyaheTextFormatter.serializeToJson(result), HttpStatus.OK);
    }
    else {
        result = new BiyaheApplicationResult("ERROR", null, ERROR_CODE_INSUFFICIENT_BALANCE, ERROR_DISPLAY_INSUFFICIENT_BALANCE);
        return new ResponseEntity(BiyaheTextFormatter.serializeToJson(result), HttpStatus.NOT_ACCEPTABLE);
    }
}

In my Servlet Context

<mvc:annotation-driven />

<mvc:cors>
    <mvc:mapping path="/api/**"
                 allowed-origins="http://localhost:9000/"
                 allowed-methods="POST, GET, PUT, OPTIONS, DELETE"
                 allowed-headers="X-Auth-Token, Content-Type, Authorization"
                 exposed-headers="custom-header1, custom-header2"
                 allow-credentials="false"
                 max-age="4800" />

    <mvc:mapping path="/**"
                 allowed-origins="http://localhost:9000/"
                 allowed-methods="POST, GET, PUT, OPTIONS, DELETE"
                 allowed-headers="X-Auth-Token, Content-Type, Authorization"
                 exposed-headers="custom-header1, custom-header2"
                 allow-credentials="false"
                 max-age="4800" />
</mvc:cors>

In my web console, I am getting -> "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8088/booking/api/saveTransaction. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)."

I have these 2 different domains: localhost:9000 and localhost:8088

localhost:9000 needs to post to localhost:8088

Note: I already done this in PHP but this time, I need to use only ajax

I have been working on this for 3 days, so if happens that there is someone who has an answer for this, please help me. Thank you in advance!

Mykel
  • 11
  • 3
  • You need to post all the relevant server side code and configuration if you hope to get an answer. – Robert Moskal Jul 06 '17 at 02:46
  • possible duplicate https://stackoverflow.com/questions/5750696/how-to-get-a-cross-origin-resource-sharing-cors-post-request-working – Scary Wombat Jul 06 '17 at 02:47
  • The receiving host needs to respond with a `Access-Control-Allow-Origin: *` header, you could set this in an `.htaccess` file on the server. – Cyclonecode Jul 06 '17 at 02:49
  • thank you @RobertMoskal, I edited my post and inserted my controller method and my servlet context – Mykel Jul 06 '17 at 03:10
  • @Cyclonecode, I'm new in spring. Can you walk me through on how to do that? – Mykel Jul 06 '17 at 03:13

1 Answers1

0

CORs can be tricky, but I think your problem here is simply that you aren't return the "Access-Control-Allow-Origin" header to your client. You can see that in the strophes of your servlet context.

First thing you might try is to simply remove the strophe, that should allow for all headers.

Robert Moskal
  • 21,737
  • 8
  • 62
  • 86