react vue前端请求后端 跨域访问样例

2 篇文章 0 订阅

 本机访问

const proxy = require("http-proxy-middleware");

module.exports = function (app) {
    app.use(proxy("/xxxx-base-manage", {
        target: "http://127.0.0.1:11020",
        changeOrigin: true,
        pathRewrite: { "^/xxxx-base-manage": "" }
    }));

    app.use(proxy("/xxxx-base-biz", {
        target: "http://127.0.0.1:10021",
        changeOrigin: true,
        pathRewrite: { "^/xxxx-base-biz": "" }
    }));

    app.use(proxy("/xxxx-info-manage", {
        target: "http://127.0.0.1:11011",
        changeOrigin: true,
        pathRewrite: { "^/xxxx-info-manage": "" }
    }));

    app.use(proxy("/xxxx-auth-center", {
        target: "http://127.0.0.1:10022",
        changeOrigin: true,
        pathRewrite: { "^/xxxx-auth-center": "" }
    }));
};

 服务器访问

          去掉pathRewrite即可。

 

React前端模拟后端接口返回PDF文件流通常涉及以下步骤: 1. 创建一个模拟的后端接口,使用一些node库如`express`和`fs`来读取文件并返回文件流。 2. 在React前端,使用`fetch`或者`axios`等HTTP客户端库发起请求到模拟的后端接口,并指定响应类型为`blob`。 3. 从响应中获取到的`blob`对象可以使用`URL.createObjectURL`创建一个可以下载的URL,然后通过`<a>`标签的`href`属性或者使用`window.open`方法触发下载。 下面是一个简单的示例实现: 后端代码示例(使用Node.js): ```javascript const express = require('express'); const fs = require('fs'); const app = express(); app.get('/download-pdf', (req, res) => { const pdfPath = 'path/to/your/file.pdf'; fs.readFile(pdfPath, (err, data) => { if (err) { res.status(500).send('Error reading file'); return; } res.setHeader('Content-Type', 'application/pdf'); res.setHeader('Content-Disposition', 'attachment; filename=yourfile.pdf'); res.end(data); }); }); app.listen(3000, () => { console.log('Server running on port 3000'); }); ``` 前端React代码示例: ```javascript function downloadPDF() { fetch('/download-pdf') .then(response => response.blob()) .then(blob => { const url = window.URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = 'yourfile.pdf'; document.body.appendChild(a); a.click(); a.remove(); }) .catch(error => { console.error('Error downloading file:', error); }); } // 调用downloadPDF函数来触发下载 downloadPDF(); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

三月泡

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值