【发布时间】:2014-08-14 09:53:06
【问题描述】:
我正在开发一个 spring mvc rest api。我在回复中添加了Access-Control-Allow-Origin。
使用 PostMan,我找到了这样的标题:
Access-Control-Allow-Methods →POST, GET, OPTIONS, DELETE
Access-Control-Allow-Origin →*
Content-Type →application/json;charset=UTF-8
Server →Apache-Coyote/1.1
Transfer-Encoding →chunked
但是当我用 test.html 测试它时,它显示错误:
XMLHttpRequest cannot load http://localhost:8080/rest/v1/tokens. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
我不知道为什么,因为 Postman,Access-Control-Allow-Origin 已经在那里了。可能是application/json的问题?
Ajax 部分:
function tokens_Post(username,password){
$.ajax({
type:"POST",
url:"http://localhost:8080/rest/v1/tokens",
dataType: "json",
contentType : "application/json",
data:{username:username,password:password},
success:show_user_info,
error:checkError
});
}
服务器代码:
@RequestMapping(value = RestURIConstants.TOKEN_POST, method = RequestMethod.POST)
public @ResponseBody ResponseEntity<Token> TokenPOST(
@RequestBody User user, HttpServletRequest rq, HttpServletResponse rp) {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<Token> response =
restTemplate.postForEntity(Token_post_url, user, Token.class);
rp.addHeader("Access-Control-Allow-Origin", "*");
rp.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response = new ResponseEntity<Token>(response.getBody(), HttpStatus.OK);
System.out.println(response.getBody().toString());
return response;
}
服务器代码,它使用另一个rest api。
转换器
<!-- Configure to plugin JSON as request and response in method handler -->
<beans:bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<beans:property name="messageConverters">
<beans:list>
<beans:ref bean="jsonMessageConverter"/>
</beans:list>
</beans:property>
</beans:bean>
<!-- Configure bean to convert JSON to POJO and vice versa -->
<beans:bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
</beans:bean>
【问题讨论】:
-
你能在test.html中显示你的ajax调用代码吗?
-
@WornOutSoles 我添加了它。这是一个获取令牌的简单函数。
-
@GGrec 谢谢,但我更喜欢你喜欢这个问题 XDD。我在这里停了两天。没有想法
标签: java http jakarta-ee web cors