为CORS添加Access-Control-Allow-Origin

时间:2014-06-24 08:10:49

标签: java http java-ee web cors

我正在开发一个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. 

我不知道为什么,因为邮差,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>   

1 个答案:

答案 0 :(得分:1)

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

同样更改data:JSON.stringify({username:username,password:password}),