gpt4 book ai didi

javascript - Access-control-allow-origin 无法在 POST 请求中使用 ajax

转载 作者:行者123 更新时间:2023-12-02 12:18:20 25 4
gpt4 key购买 nike

我的标题“Access-control-allow-origin”有问题,我使用下一个代码来发出请求:

<script type='text/javascript'>
function save() {
$.ajax(
{
type: 'POST',
url: "...",
contentType: 'application/json',
data: '{"cuspp":"228061JGLIR5", "userWeb":"46689"}',
success: function (data) {
console.log("It Works");
console.log (data);
if (data.codigo==0){
console.log(data.mensaje);
}else{
console.log(data.mensaje);

}
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("error");
}
});
}
</script>

以及 java 客户端做出的响应:

@POST
@Path("/pcnct020")
@ApiOperation(value = "Save events.", notes = "PCNCT020", responseClass =
"data.Answer")
public Response saveEvents(
@ApiParam(value="Structure of Event", required = false) Evento event) {


Answer<Result> answer = Validator.validate(event);

if (answer.esOK()) {

int size = event.textDetail.length();

int count = size / 60;

String comment = event.textDetail;
int secuence = 0;

for (int j = 0; j <= count; j++) {
evento.secuence = secuence;
String newString;

if (j == 0) {
if (size < 60) {
newString = comment.substring(j * 60);

} else {
newString = comment.substring(j * 60,
(j * 60) + 60);
}

} else if (j == count) {
newString = comment.substring(j * 60);
if (newString.equals("")) {
break;
}

} else {
newString = comment.substring(j * 60,
(j * 60) + 60);
if (newString.equals("")) {
break;
}
}
event.textDetail = newString;
answer.setAnswer(event.saveEvent());
secuence = Integer.parseInt(answer.ans.status);
}

}
return Response
.status(200)
.header("Access-Control-Allow-Origin", "...")
//.header("Access-Control-Allow-Credentials", "true")
//.header("Access-Control-Allow-Headers", "Origin")
//.header("Access-Control-Allow-Methods", "GET, POST, DELETE,
PUT, PATCH, HEAD, OPTIONS")
//.header("Conten-Type","application/application/json")
.entity(answer)
.build();

}

当尝试从 header “Access-Control-Allow-Origin”指示的地址访问时,在浏览器控制台中出现此错误:

XMLHttpRequest 无法加载 http://sdpeapp00024.pe.intranet:9080/ccws/rest/ops/pcnct020 。对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin” header 。来源'http://i6.sura.pe ' 因此不允许访问。

我不知道我还能做什么。我尝试添加其他 header ,例如 java 代码响应中的注释,但总是遇到相同的错误。

非常感谢您的帮助。

更新:

  public void getService(){

try {

String urlWS = "Web Service Url";

String url = urlWS;

CloseableHttpClient httpclient = HttpClients.createDefault();

HttpPost httpPost = new HttpPost(url);

httpPost.setHeader("Content-type", "application/json");

StringEntity params =new StringEntity("
{\"cuspp\":\"228061JGLIR0\", \"usuarioWeb\":\"46683\");


httpPost.setEntity(params);


CloseableHttpResponse response =
httpclient.execute(httpPost);

System.out.println(response.getStatusLine());

System.out.println(response.getStatusLine().getStatusCode());

if(response.getStatusLine().getStatusCode() == 200){
BufferedReader brResponse = new BufferedReader(new
InputStreamReader(response.getEntity().getContent()));
String responseText = "";
String output = "";
while ((output = brResponse.readLine()) != null) {
responseText += output;
}
System.out.println(responseText);


}

} catch (Exception excepcion) {
System.out.println(excepcion.toString());
}
finally{

}
}

我用java做了一个客户端并且工作正常。我真的不知道为什么使用 Ajax 不起作用,但这表明 Web 服务工作正常,问题出在客户端。

问候。

PS。在代码中,我没有放置网址,因为不允许我发布两个以上的网址,但它们与错误消息中显示的网址相同。

最佳答案

我发现的解决方案是使用以下代码创建一个实现 ContainerResponseFilter 接口(interface) (com.sun.jersey.spi.container) 的新类:

@Provider
public class SummerResponseFilter implements ContainerResponseFilter {

@Override
public ContainerResponse filter(ContainerRequest request, ContainerResponse response)
{

//INICIO OT 10533 - PSC001
String ruta = request.getPath();

if(ruta.contains("pcnct020")){
response.getHttpHeaders().add("Access-Control-Allow-Origin", "*");
response.getHttpHeaders().add("Access-Control-Allow-Methods","GET, OPTIONS,
HEAD, PUT, POST");
response.getHttpHeaders().add("Access-Control-Allow-Headers","Content-Type");

}

//FIN OT 10533 - PSC001

if (Logger.isDebugEnabled()) {
Logger.debug("Finaliza el proceso de la url [%s] %s", request.getMethod(),
request.getRequestUri().toString());
}
if (Logger.isTraceEnabled()) {
Logger.trace("Response - Headers = [ %s ]",
response.getHttpHeaders().toString());
Logger.trace("Response - Status = [ %d ]", response.getStatus());
}
Answer.clean();
return response;
}

}

然后在xml中这样定义:

 <init-param>
<param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
<param-value>filter.SummerResponseFilter</param-value>
</init-param>

通过这个解决方案,我可以解决我的问题。我希望可以帮助有同样问题的人。

感谢您的回答。

关于javascript - Access-control-allow-origin 无法在 POST 请求中使用 ajax,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45987507/

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