gpt4 book ai didi

java - 为 CROS 添加 Access-Control-Allow-Origin

转载 作者:行者123 更新时间:2023-12-01 12:49:10 25 4
gpt4 key购买 nike

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

最佳答案

在 ajax 属性中添加 crossDomain : true

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

关于java - 为 CROS 添加 Access-Control-Allow-Origin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24381486/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com