1

I'm developping an upload feature using an Ajax upload on a Spring Rest service. It works fine on the development server, but once on the integration server, which has a configuration similar to production and needs a cross-plateform call, I get the dreaded

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.

in my Javascript console.

Here a piece of the JSP with the Javascript code of the upload:

  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);

From Spring controller:

@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);
    }
...
}

From my web.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>

And here the code from the filter:

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);
    }
}

I'm using Java 7, Tomcat 7 and Spring 3.0.4.

Edit: I just saw, if I log (I can't debug on that server) the request.getHeader("Access-Control-Request-Method"), it's null. But request.getMethod() returns "POST". Is that normal?

Edit 2: My rest call uses a POST method, a with multipart/form-data content type and no custom headers, so it doesn't require a preflight call. Anyway, I forced a preflight call by adding a custom header and authorizing it in my Access-Control-Allow-Headers response header. Now, I can see the 2 calls in browser's network console. And the strange thing: my preflight OPTIONS call passes wthout any problem, but my POST call still causes "No 'Access-Control-Allow-Origin' header is present on the requested resource". I really don't get it.

Edit 3: Ok, now we are getting somewhere. It seems browsers misinterpret a 500 error from the server as a cross-domain error when in cross-domain situation. And when I look in the localhost.log, I actually see an exception:

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)

The problem is now: I can see the multipart file called "file_up" in my request in the network view on Chrome, so I still don't get why it doesn't work.

Request payload:

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


------WebKitFormBoundaryi7iVj0nFvRL8zcuy--

The mystery thickens...

Alexis Dufrenoy
  • 11,784
  • 12
  • 82
  • 124
  • It looks a lot like an identified problem, but even when I add a multipartResolver and a multipartFilter, it still doesn't work. But I'm making progress. – Alexis Dufrenoy Jan 17 '17 at 16:47

2 Answers2

1

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

And I think you need to add OPTIONS in your methods too.

  • I added "Content-Range, Content-Disposition, Content-Description" to my "Access-Control-Allow-Headers" header and "OPTIONS" to "Access-Control-Allow-Methods", but I still get the same error. – Alexis Dufrenoy Jan 13 '17 at 14:18
0

I finally solved my issue. Turns out it wasn't a real cross-domain problem, but a 500 internal error the browser misinterpreted as a cross-domain access error, which is something that can happen on a usual basis when a cross-domain call takes place and a 500 error is occuring. A point to keep in mind when adressing cross-domain errors.

My real problem was an easy Spring configuration problem, but somehow the missing parameters didn't prevent the code from working on my local Tomcat installation, which I still don't understand.

Alexis Dufrenoy
  • 11,784
  • 12
  • 82
  • 124
  • Thank you to @troelskn for pointing me in the right direction with his comment here: http://stackoverflow.com/questions/10143093/origin-is-not-allowed-by-access-control-allow-origin – Alexis Dufrenoy Jan 18 '17 at 09:36