有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

javascript跨平台Ajax上载不工作

我正在Spring Rest服务上开发一个使用Ajax上传的上传功能。它在开发服务器上运行得很好,但一旦在集成服务器上运行,它的配置类似于生产,需要跨平台调用,我就会感到害怕

XMLHttpRequest cannot load http://xxxxxxxxxx:7001/felixmetier/rest/upload/montants. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://yyyyyyy' is therefore not allowed access. The response had HTTP status code 500.

在我的Javascript控制台中

下面是一段带有上传Javascript代码的JSP:

  var xhr = new XMLHttpRequest();
  if ("withCredentials" in xhr) {
    xhr.withCredentials = true;
    xhr.open('POST', '<%=Environment.getServiceParameter("FELIX", "rest.service.saisieMontants.upload.url")%>', true);
  } else if (typeof XDomainRequest != "undefined") {
    xhr = new XDomainRequest();
    xhr.open('POST', '<%=Environment.getServiceParameter("FELIX", "rest.service.saisieMontants.upload.url")%>');
  } else {
    throw new Error('Accès cross-platform interdit sur ce navigateur. Utilisez un navigateur plus récent (IE 8+, Chrome 3+, Firefox 3.5+, Safari 4+).');
  }
  xhr.onload = function () {
    activateFormButtonsAndLinks();
    document.getElementById('fwkWaitingScreen').style.display = 'none';
    var response = this.responseText;
    var data = JSON.parse(response);

    if (data.status===1) {
        alert("Erreur générale lors du chargement (pas de mise à jour en BDD) : "+data.message);
    } else {
        var msg = "Chargement terminé.\n\nNb de lignes traitées : "+data.totLines+"\nNb de lignes déjà controlées : "+data.totControlled+"\nNb de lignes inexistantes en BDD : "+data.totIgnored

        if (data.status===2) {
            msg = msg + "\n\n"+data.totError+" erreur se sont produires lors du chargement. Lignes en erreur (max. "+data.maxError+" affichées) : "+data.errorLines
        } else {
            msg = msg + "\n\n"+"Chargement OK";
        }

        alert(msg);
    }

    var rechBouton = document.getElementsByName("recherche").item(0);

    doAction(rechBouton, '','rechercherbouton');
  }

  xhr.send(formData);

从Spring控制器:

@Controller
public class MontantsUploadController {
...

    @RequestMapping(value = "/upload/montants", method = RequestMethod.POST)
    public ResponseEntity<?> upload(@RequestParam("file_up") MultipartFile file, HttpServletRequest request) {
        InputStream is;
        SaisieMontantsUploadRestResponse feedback = null;
        try {
            is = file.getInputStream();
            Reader reader = new InputStreamReader(is);

            feedback = parseImportedFile(reader, "guest", getLocale(request));
        } catch (IOException e) {
            feedback = new SaisieMontantsUploadRestResponse();
            feedback.setMessage("Impossible de lire le fichier attaché");
            feedback.setStatus(SaisieMontantsUploadRestResponse.STATUS_GENERAL_ERROR);
            log.error("Impossible de traiter le CSV", e);
        }

        backupFile(file);

        return new ResponseEntity<SaisieMontantsUploadRestResponse>(feedback, HttpStatus.OK);
    }
...
}

从我的网站。xml:

<filter>
    <filter-name>CORS</filter-name>
    <filter-class>fr.xxxx.felix.ejb.restjson.filter.CorsFilter</filter-class>
</filter>

<!-- Applying the CORS Filter to All REST URL -->
<filter-mapping>
    <filter-name>CORS</filter-name>
    <url-pattern>/rest/*</url-pattern>
</filter-mapping>

下面是来自过滤器的代码:

public class CorsFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
        response.addHeader("Access-Control-Allow-Headers", "Content-Type");
        response.addHeader("Access-Control-Max-Age", "30");

        filterChain.doFilter(request, response);
    }
}

我正在使用Java 7、Tomcat 7和Spring 3.0.4

编辑:我刚刚看到,如果我记录request.getHeader("Access-Control-Request-Method")(我无法在该服务器上调试),它将为空。但是request.getMethod()返回“POST”。这正常吗

编辑2:我的rest调用使用一个POST方法,一个具有多部分/表单数据内容类型且没有自定义标题的方法,因此它不需要飞行前调用。无论如何,我通过添加一个自定义头并在我的Access Control Allow Headers response头中对其进行授权,来强制执行一个飞行前呼叫。现在,我可以在浏览器的网络控制台中看到这两个调用。奇怪的是:我的飞行前选项调用没有任何问题,但我的POST调用仍然会导致“请求的资源上没有“Access Control Allow Origin”头”。我真的不明白

编辑3:好的,现在我们有进展了。在跨域情况下,浏览器似乎将服务器的500错误误解为跨域错误。当我查看本地主机时。日志,我实际上看到了一个例外:

org.springframework.web.bind.MissingServletRequestParameterException: Required MultipartFile parameter 'file_up' is not present
        at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter$ServletHandlerMethodInvoker.raiseMissingParameterException(AnnotationMethodHandlerAdapter.java:715)
        at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveRequestParam(HandlerMethodInvoker.java:511)
        at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveHandlerArguments(HandlerMethodInvoker.java:340)
        at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:171)
        at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:427)
        at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:415)
        at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:788)
        at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:717)
        at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
        at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:560)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
        at fr.xxxxx.felix.ejb.restjson.filter.CorsFilter.doFilterInternal(CorsFilter.java:77)
        at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
        at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
        at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
        at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
        at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
        at java.lang.Thread.run(Thread.java:745)

现在的问题是:在Chrome上的网络视图中,我可以在我的请求中看到名为“file_up”的多部分文件,所以我仍然不明白它为什么不起作用

请求有效载荷:

------WebKitFormBoundaryi7iVj0nFvRL8zcuy
Content-Disposition: form-data; name="file_up"; filename="test_SAISIE_DES_MONTANTS.csv"
Content-Type: application/vnd.ms-excel


------WebKitFormBoundaryi7iVj0nFvRL8zcuy--

谜团越来越深


共 (2) 个答案

  1. # 1 楼答案

    试试
    response.addHeader("Access-Control-Allow-Headers", "Content-Type, Content-Range, Content-Disposition, Content-Description");

    我认为你也需要在你的方法中添加选项

  2. # 2 楼答案

    我终于解决了我的问题。事实证明,这不是一个真正的跨域问题,而是一个500内部错误。浏览器错误地将其解释为跨域访问错误。通常,当跨域调用发生并且出现500错误时,会发生这种情况。处理跨域错误时要记住的一点

    我真正的问题是一个简单的Spring配置问题,但不知何故,缺少的参数并没有阻止代码在我本地的Tomcat安装上工作,我仍然不理解