react中使用nextjs框架,前端调后端接口跨域解决方式

前端在项目目录中next.config.js文件中添加以下代码

async rewrites() {
    return [
      {
        source: "/api/:path*",
        destination: `${process.env.NEXT_PUBLIC_API_DOMAIN}/api/:path*`,
        basePath: false
      }
    ]
  }

截图:

  • source: "/api/:path*": 定义了一个 URL 模式,匹配所有以 /api/ 开头的请求,并将 :path* 作为一个通配符来匹配其后的路径部分。

  • destination: "${process.env.NEXT_PUBLIC_API_DOMAIN}/api/:path*": 将匹配的请求代理到 NEXT_PUBLIC_API_DOMAIN 所定义的后端 API。process.env.NEXT_PUBLIC_API_DOMAIN 是一个环境变量,通常在 .env 文件中定义。例如,如果 NEXT_PUBLIC_API_DOMAIN (后端接口ip:端口)的值是 https://api.example.com,那么请求 http://localhost:3000/api/users 就会被代理到 https://api.example.com/api/users

  • basePath: false: 禁用 basePath,确保重写规则不受 basePath 配置的影响。

注意:不要配置axios的baseURL,让其默认是localhost:xxx地址请求接口,它会转发到${process.env.NEXT_PUBLIC_API_DOMAIN}/api/:path*地址

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
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值