Night bothers me a question, finally resolved, I just began to use the ajax to manipulate results always show a blank screen, then use native, and axios are normal, paste the code bar
node code simulates the background there is a background test can be ignored
var express = require('express')
var router = express.Router()
var fs = require('fs')
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' })
})
router.post('/getPdf', function(req, res, next) {
// 这里设置是为了让前端访问是预览形式,而不是下载
res.set('Content-Type', 'application/pdf')
fs.readFile('/test.pdf', (err, data) => {
if (err) {
console.log('报错了:', err)
} else {
console.log('传出数据:', data)
// 好多说的是返回data.toString(),但类型会错误,因为是express封装过,直接data返回就好
res.send(data)
}
})
})
The first front-end code trial and error, at least an hour to fiddle around with a blob or responseType arraybuffer, the result is ajax request which will not work, naked blank pdf online preview, Oh!
$.ajax({
url: 'http://127.0.0.1:3000/getPdf',
type: 'POST',
responseType: 'blob',
data: {},
success: function(res) {
var blob = new Blob([res], {
type: 'application/pdf;chartset=UTF-8'
})
var fileURL = URL.createObjectURL(blob)
window.open(fileURL)
},
error: function(err) {
console.log('失败:', err)
}
})
The second trial and error, original request, which can be directly displayed, but previous attempts I feel a little waste of time, I would like to try axiso confirm what is ajax problem
var xhr = new XMLHttpRequest()
xhr.open('POST', 'http://127.0.0.1:3000/getPdf', true)
xhr.responseType = 'blob'
xhr.onload = function() {
if (this.status == 200) {
var blob = this.response
var fileURL = URL.createObjectURL(blob)
var Dom = `<object data="${fileURL}" type="application/pdf" style="width: 400px; height: 400px;"></object>`
$('body').append(Dom)
// window.open(fileURL)
}
}
xhr.send()
The third trial and error, axios, try and concluded that in addition to ajax, it seems all right
axios({
methods: 'POST',
url: 'http://127.0.0.1:3000/getPdf',
responseType: 'blob'
}).then(res => {
var blob = new Blob([res.data], {
type: 'application/pdf;chartset=UTF-8'
})
let fileURL= URL.createObjectURL(blob)
// 下载代码
// let downEle = document.createElement('a')
// let fname = `download` //下载文件的名字
// downEle.href = fileURL
// downEle.setAttribute('download', fname)
// document.body.appendChild(downEle)
// downEle.click()
window.open(fileURL)
})