我知道已经有很多关于此错误的问题。但是,即使设置标题后我仍然无法正常工作
"Access-Control-Allow-Origin" : "*"
在我的服务器端。
这是我的 spring mvc Controller 方法:
@RequestMapping(method=RequestMethod.GET, value="dummy/{num}")
@ResponseBody
public ResponseEntity<Result> dummy(@PathVariable String num)
{
int n = Integer.parseInt(num);
final Result result = new Result();
result.setAddition(n+20);
result.setMultiplication(n*20);
result.setSubtraction(n-20);
HttpHeaders headers = new HttpHeaders();
headers.add("Access-Control-Allow-Origin", "*");
ResponseEntity<Result> ent = new ResponseEntity<Result>(result,headers,HttpStatus.CREATED);
return ent;
}
这是我从 Jquery 进行的 AJAX 调用
$.ajax({
url: "http://localhost:8010/Probe_Rest_Service/test/dummy/9",
type: "get",
crossDomain: true,
dataType: 'json',
headers: {
"Content-type" : "application/json"
},
success: function(data){
console.log("It worked!");
alert(data);
},
error: function(){
// enable the inputs
alert("error");
}
});
我尝试从 chrome 的 dev-http 客户端调用我的 REST api,它工作正常(响应 header 设置了 Access-Control-Allow-Origin:* )。但是,当我从 html 文件调用它时,我收到错误。
我使用 JBoss 作为我的其余 api,使用 tomcat 来托管我的客户端网页
最佳答案
由于您发送的请求内容类型为 application/json
,客户端被迫执行 CORS 预检请求。
CORS specification表示除 application/x-www-form-urlencoded
、multipart/form-data
或 text/plain
之外的任何内容类型都需要飞行前请求以确定是否允许该 header 。
因此,您需要处理飞行前请求(HTTP 方法 = OPTIONS
)。
为了简单起见,让服务器响应 header :
Access-Control-Allow-Headers: *
这将允许所有请求 header 。
更新
我再次阅读了您的问题,发现了一些我不明白的地方:为什么您首先要为 HTTP GET 请求发送 Content-Type
header ?这是不正确的。
直接删除
headers: {
"Content-type" : "application/json"
}
然后重试。这可能会解决它!
关于jquery - Access-Control-Allow-Origin 不允许来源 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15510427/