2017-07-06 72 views
1

好的,這是我第一次在這裏發佈,所以如果你看到我需要糾正一些問題,請告訴我。Ajax發佈請求結果到跨源請求被阻止:同源策略不允許讀取遠程資源

我在嘗試使用ajax將數據發佈到api時遇到了問題。我使用tomcat8作爲我的網絡服務器。我在其他人建議的控制器中添加了@CrossOrigin註釋。我還在我的servlet.xml中添加了localhost:9000作爲allowed-origin和Authorization in allowed-headers,但仍然沒有成功。

這是我的Ajax代碼:

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); 
        } 
       }); 

在我的控制器

@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":"[email protected]", 
      "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); 
    } 
} 

在我的servlet上下文

<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> 

在我的Web控制檯,我得到 - >「跨-Origin Request Blocked:同源策略不允許在http://localhost:8088/booking/api/saveTransaction處讀取遠程資源(原因:COR S標題'Access-Control-Allow-Origin'缺失)。「

我有這兩個不同的領域:本地主機:9000和本地主機:8088

本地主機:9000需要發佈到本地主機:8088

注:我已經在PHP但這次做到了這一點,我只需要使用 AJAX

我一直在這3天,所以,如果碰巧是誰的人有這樣一個答案,請幫助我。先謝謝你!

+0

如果您希望得到答案,您需要發佈所有相關的服務器端代碼和配置。 –

+0

可能的重複https://stackoverflow.com/questions/5750696/how-to-get-a-cross-origin-resource-sharing-cors-post-request-working –

+0

接收主機需要用'Access- Control-Allow-Origin:*'標題,你可以在服務器上的.htaccess文件中設置它。 – Cyclonecode

回答

0

CORs可能會很棘手,但我認爲您的問題在於您不會將「Access-Control-Allow-Origin」標題返回給您的客戶端。你可以在servlet上下文的strophes中看到。

你可能會嘗試的第一件事就是簡單地刪除strophe,它應該允許所有頭文件。

+0

謝謝羅伯特莫斯卡爾! – Mykel

相關問題