簡體   English   中英

為CROS添加訪問控制允許來源

[英]Add Access-Control-Allow-Origin for CROS

我正在開發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>   

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

同樣更改如下data:JSON.stringify({username:username,password:password}),

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM