【发布时间】:2015-05-13 00:33:54
【问题描述】:
我有一个基于 @RestController 和 AngularJS 的简单项目。 我可以从 Angular 向 @RestController 发送 GET 请求,但我无法发送 POST 请求。我在浏览器控制台中有错误:
XMLHttpRequest 无法加载 http://localhost:8080/add。 Access-Control-Allow-Headers 不允许请求标头字段 Content-Type。
我的@RestController:
@RestController
public class AngularController {
//@Autowired
// PhraseService phraseService;
Logger logger = LoggerFactory.getLogger(this.getClass());
@RequestMapping(value = "/add", method = RequestMethod.POST)
public void add(@RequestBody String str){
logger.info("Added");
logger.info(str);
}
@RequestMapping("/")
public void angularController(){;
logger.info("Request!");
}
}
这是我的 CORS 过滤器:
@Component
public class SimpleCORSFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
response.setHeader("Content-Type", "application/json");
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {}
public void destroy() {}
}
我的 AngularJS 控制器:
function addController($scope, $http){
$scope.url = 'http://localhost:8080/add';
$scope.addPhrase = function(){
$http.post($scope.url, {"data": $scope.value});
}
}
还有index.html:
<!doctype html>
<html ng-app>
<head>
<title>Hello AngularJS</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script src="server.js"></script>
</head>
<body>
<div ng-controller="addController">
<form>
<input type="text" np-model="value"/>
<button type="button" ng-click="addPhrase()">Send!</button>
</form>
</div>
</body>
</html>
我试图用 header: "Content-Type": "application/json" 解决这个问题,但它给了我 Bad request 错误。
【问题讨论】:
-
检查this,您可能需要将
"Content-Type"添加到response.setHeader("Access-Control-Allow-Headers", "x-requested-with")行。
标签: angularjs spring post cors