0

I implement a REST API as follow. Browser - as a client - could not executes my javascripts given from mentioned REST and prints errors such as Refused to execute script from 'http://localhost:8083/vendor.js' because its MIME type ('') is not executable, and strict MIME type checking is enabled. It means that MIME type is not set for response while I set content-type for response but it is applied.

@RequestMapping(value = "/{resoucePath:.+}", method = RequestMethod.GET)
public void getResouce(@PathVariable String resoucePath, HttpServletResponse response) {
    String myPath = ...; // I set resource path here
    File resouce = new File(myPath);
    try {
        InputStream is = new FileInputStream(resouce);
        IOUtils.copy(is, response.getOutputStream());
        response.setContentType(mimeTypesMap.getContentType(resouce));
        response.flushBuffer();
    } catch (IOException ex) {
        // log error
        throw new RuntimeException("IOError writing file to output stream", ex);
    }
}

What is my mistake? Why content-type is not set in response?

hadi.mansouri
  • 828
  • 11
  • 25
  • refer https://stackoverflow.com/questions/4471584/in-spring-mvc-how-can-i-set-the-mime-type-header-when-using-responsebody – harshavmb Jun 23 '17 at 02:44
  • @harshavmb accepted response to mentioned question suggests to use produces property for RequestMapping but my mime-type is dynamic. My case would be work by this answer: https://stackoverflow.com/a/4471956/5538979. My code is similar to this answer but it is not work! – hadi.mansouri Jun 23 '17 at 09:51

1 Answers1

0

I found the problem. Content type is not applied because it is set after writing response. I reorder following lines and problem is resolved:

Problematic code:

IOUtils.copy(is, response.getOutputStream());
response.setContentType(mimeTypesMap.getContentType(resouce));

Resolved code:

response.setContentType(mimeTypesMap.getContentType(resouce));
IOUtils.copy(is, response.getOutputStream());
hadi.mansouri
  • 828
  • 11
  • 25