前端请求下载(react)

let oReq = new XMLHttpRequest();
oReq.open("GET", getUrl(requestUrlBase, `/******`), true);
oReq.responseType = "blob";
oReq.setRequestHeader("Content-Type", "application/octet-stream", 'cors', "Access-Control-Allow-Origin", "*");
oReq.setRequestHeader("xToken", "854566eb00534affa8cfe16d05bfdbf5");
oReq.onload = function (oEvent) {
  let content = oReq.response;
  console.log('oReq.response', oReq.response)
  let elink = document.createElement('a');
  elink.download = 'cs.xlsx';//xls   因为后台输入是csv'格式,用xls显示的不理想      
  elink.style.display = 'none';
  let blob = new Blob([content]);
  elink.href = URL.createObjectURL(blob);
  document.body.appendChild(elink);
  elink.click();
  document.body.removeChild(elink);

};
oReq.send();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以在 React 中使用 fetch API 来实现,具体实现方法如下:1. 使用 fetch 函数发起一个请求,指定请求头中的 credentials 字段,设定为 'include';2. 在 fetch 的第二个参数中指定 credentials 字段,设定为 'include';3. 如果需要,可以在 fetch 的第三个参数中指定要发送的 cookie,使用 credentials 字段,设定为 'include'。 ### 回答2: 在React中实现前端请求携带cookie可以通过以下步骤完成: 1. 首先,确保在React项目中安装了axios或者其他的网络请求库。可以使用以下命令安装axios: ``` npm install axios ``` 2. 在React组件中导入axios: ```javascript import axios from 'axios'; ``` 3. 创建一个请求时需要携带cookie的函数: ```javascript const requestWithCookie = async () => { try { const response = await axios.get('https://example.com', { withCredentials: true }); console.log(response); } catch (error) { console.error(error); } }; ``` 4. 调用该函数发送请求并携带cookie: ```javascript requestWithCookie(); ``` 在上述代码中,调用`axios.get`函数时,我们将`{ withCredentials: true }`作为第二个参数传递给方法,这样可以告诉axios在发送请求时包含浏览器上持有的cookie。 需要注意的是,后端服务器也需要正确地设置响应头以允许跨域请求携带cookie,通常可以使用以下代码来实现: ```javascript response.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000'); response.setHeader('Access-Control-Allow-Credentials', 'true'); ``` 前端请求携带cookie的实现方法适用于需要进行用户身份认证、会话管理或其他需要使用cookie来维护状态的场景。 ### 回答3: 在React中实现前端请求携带cookie,我们可以通过一些方法来实现。 首先,确保后端在响应请求时设置了cookie。这可以通过使用后端框架或库来实现,在响应头中添加Set-Cookie字段。 然后,在前端中,我们可以使用fetch或axios等库来发送请求。这些库提供了一些选项,允许我们将cookie包含在请求中。以下是使用fetch库的一个示例: ```javascript fetch('https://example.com/api', { credentials: 'include' }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.log(error)); ``` 在上面的代码中,我们通过设置credentials选项为'include',告诉fetch库在请求中包含cookie。这样,后端就可以通过读取请求中的cookie来验证用户的身份或执行其他操作。 类似地,如果使用axios库,可以通过设置withCredentials选项来实现相同的效果: ```javascript axios.get('https://example.com/api', { withCredentials: true }) .then(response => console.log(response.data)) .catch(error => console.log(error)); ``` 通过以上的方式,我们就可以在React中实现前端请求携带cookie。这样,后端可以在处理请求时读取cookie,实现相关的业务逻辑。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值