简体   繁体   中英

Error: Resource interpreted as Document but transferred with MIME type application/pdf

I am sending a PDF stream from my server to the client and then displaying that PDF in an <object> tag in the client. Here is my code:

server.js

router.get('/pdf', function * () {
  var stream = getMyFileStream();
  this.set('Content-Type', 'application/pdf');
  this.response.body = stream;
});

client.js

var objectElement = document.querySelector('object');

fetch('/pdf', request)
  .then(res => res.blob())
  .then(blob => URL.createObjectURL(blob))
  .then(url => {
    objectElement.setAttribute('data', url)
    objectElement.setAttribute('type', 'application/pdf')
  })

This code seems to work correctly, however I get the following warning in my console:

Resource interpreted as Document but transferred with MIME type application/pdf

Why does it think my resource should be text/html ? If I change my Content-Type header to text/html , it makes the warning go away but it obviously causes a rendering issue of the PDF. Any help would be appreciated.

In your fetch statement you need to set a header type because the default will be document. Since you have not specified the matching content the browser is letting you know something hooky is happening.

// to stop browser complaining use a request object to specify header
var request = new Request('/pdf', {
    headers: new Headers({
        'Content-Type': 'application/pdf'
    })
});

fetch(request)
.then(function() { /* handle response */ });
...

Note: This is from my own evaluation research of the fetch api. I have not yet used it in anger so this is untested. I found this site useful https://davidwalsh.name/fetch .

Let me know how you get on please.

Most likely this is because there's a redirect from /pdf and/or there is no file extension.

Add this extra header:

this.set('Content-Disposition', 'attachment; filename=results.pdf');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM