【问题标题】:Add Access-Control-Allow-Origin for CROS为 CROS 添加 Access-Control-Allow-Origin
【发布时间】: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


【解决方案1】:

在你的 ajax 属性中添加crossDomain : true

也改成这样data:JSON.stringify({username:username,password:password}),

【讨论】:

  • 将dataType中的json改为jsonp
  • 可能是因为它是 Access-Control-Allow-Origin →*。用“→”而不是“:”? @巴拉特
  • 你在尝试做一个 JSON 帖子吗?
  • 现在加载资源失败:服务器响应状态为 405 (Méthode Non Autorisée),也许我需要更新我的 rest api。
  • 是的。这是一个json帖子。问题出在这里?
猜你喜欢
  • 2015-09-28
  • 1970-01-01
  • 2017-12-12
  • 2011-06-27
  • 2016-07-03
  • 2017-06-15
  • 2016-09-30
  • 2015-06-17
相关资源
最近更新 更多