使用Spring和Maven,我构建和部署一个WAR项目,当地的Tomcat服务器,当我使用浏览器访问的API,它的工作原理:无法使用JQuery请求将GET API部署到本地Tomcat服务器?
http://localhost:8015/keystroke-backend/user
我:
[{"id":1,"username":"bilal","password":"pass"}]
但当我使用AJAX使用JQuery访问它时,没有发生任何事情:
$(document).ready(function() {
// Event to check the input data
$("#login-form").submit(function(e) {
e.preventDefault();
$.ajax({
url: "http://localhost:8015/keystroke-backend/user"
}).then(function(data) {
alert("success");
});
});
});
没有任何反应。
这是GET API:
@Controller
@RequestMapping("/user")
public class KeystrokeController {
@RequestMapping(method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<List<User>> doGetUsers() {
List<User> usersList = new ArrayList<User>();
try {
// Get the list of users from the database
usersList = UsersDB.getDB().getUsers();
return new ResponseEntity<List<User>>(usersList, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<List<User>>(usersList, HttpStatus.NOT_ACCEPTABLE);
}
}
}
我看到这个错误从控制台:
XMLHttpRequest cannot load http://localhost:8080/testing-client/test/server-status/1. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.
需要注意的是,当我使用相同的代码到别的访问像下面这样:
url: "http://rest-service.guides.spring.io/greeting"
它的工作原理。任何想法 ?
发表您的控制器的方法 – Lucky
@Lucky,我刚刚更新的问题 –