好的,这是我第一次在这里发帖,所以如果您发现我需要更正某些内容,请告诉我。
当我尝试使用 ajax 将数据发布到 api 时遇到问题。我使用 tomcat8 作为我的网络服务器。我在我的 Controller 中添加了其他人建议的 @CrossOrigin 注释。我还在 servlet.xml 的 allowed-headers 中添加了 localhost:9000 作为 allowed-origin 和 Authorization,但仍然没有成功。
这是我的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);
}
});
在我的 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);
}
}
在我的 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 控制台中,我收到 ->“跨源请求被阻止:同源策略不允许读取 http://localhost:8088/booking/api/saveTransaction 处的远程资源。(原因:CORS header ‘Access-Control-Allow-Origin’丢失)。”
我有这 2 个不同的域:localhost:9000 和 localhost:8088
localhost:9000 需要发布到 localhost:8088
Note: I already done this in PHP but this time, I need to use only ajax
我已经为此工作了三天,所以如果有人对此有答案,请帮助我。预先感谢您!
请您参考如下方法:
COR 可能很棘手,但我认为您的问题很简单,就是您没有将“Access-Control-Allow-Origin” header 返回给您的客户端。您可以在 servlet 上下文的节号中看到这一点。
您可能尝试的第一件事就是简单地删除节号,这应该允许所有 header 。