背景:起因想封装一个流下载组件,拿后端响应头 Content-Disposition 的 filename作为文件名,发现 浏览器有返回,但客户端 拿不到。
原因:默认情况下,浏览器不允许跨域请求的JavaScript代码访问某些响应头信息。(安全考虑)
解决方案:需要后端在接口返回增加响应头,告诉浏览器需要暴露给客户端的响应头字段。
res.setHeader('Access-Control-Expose-Headers', 'Content-Disposition');
#node模拟后端
import express from 'express';
import fs from 'fs';
import path from 'path';
const app = express();
app.use(express.json());
//解决跨域
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
res.setHeader('Access-Control-Expose-Headers', 'Content-Disposition'); //让客户端能拿到 Content-Disposition
next()
})
app.post('/download', (req, res) => {
const fileName = '1718676059620.pdf'
const filePath = path.join(process.cwd(), 'static', fileName)
const content = fs.readFileSync(filePath);
//两个相应头
res.setHeader('Content-Type', 'application/octet-stream');
res.setHeader('Content-Disposition', `attachment;filename=${fileName}`);
res.send(content);
})
app.listen(3000, () => {
console.log('server is running on port 3000');
})
#前端代码
import axios from 'axios'
function App() {
const handleClick = () => {
// axios.post("http://localhost:3000/download",).then(res => {
// console.log(res,'rrr');
// })
fetch("http://localhost:3000/download", { method: "post" }).then(res => {
console.log(res, 'res');
const ComDis = res.headers.get("content-disposition");
console.log(ComDis, 'ComDis');
})
}
return (
<>
<button onClick={handleClick}>按钮
</button>
</>
)
}
export default App
axios调用正常,发现fetch调用接口打印是个 Headers类,属性隐藏在该类中
res.headers.get("content-disposition"); 获取对应响应头