React+.Net core实现跨域操作

完美实现React+antd-UI框架实现跨域调用后端.net core接口

前端
首先需要安装
模块  npm install http-proxy-middleware --save
创建一个跨域的js文件 (setupProxy.js)

填写如下代码:
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
  app.use(
    '/api',
    createProxyMiddleware({
      target: 'Your backend request IP address',//注意此处只是ip地址没有接口
      changeOrigin: true,
    })
  );
};
在packpage.json中配置
"proxy": "Your backend request IP address"  


最后在你的请求方法中
const generateDoc = async () => {
    const options = {
      method: 'POST',
      url: '/Home/GenerateDocument', // 使用代理前缀路径 这里就是后端的接口 Home=控制器  GenerateDocument=接口
      responseType: 'arraybuffer',
      headers: {
        'Content-Type': 'application/json'
      },
     //此处传递的对象需要跟后端定义的保持一致
      data: JSON.stringify({
        Id: 'SL-004',
        Title: 'word title',
        Content: 'this is word contect'
      })
    };
  
    try {
      const response = await axios(options);
      const blob = new Blob([response.data], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = 'selected-data.docx';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    } catch (error) {
      console.error(error);
    }
  };
 后端接口接收
  [HttpPost]
public async Task<IActionResult> GenerateDocumentAsync([FromBody] Dictionary<string, List<Document>> data)
{

	try
	{
		var documents = data["documents"];
		_logger.LogInformation($"接受的前端数据 document: {JsonConvert.SerializeObject(documents) }");
		var documentBytes = await _documentService.GenerateDocumentAsync(documents);
		return File(documentBytes, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "MyDocument.docx");
	}
	catch (Exception ex)
	{
		_logger.LogError(ex.Message, ex);
		return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
	}
}

后端代码 Startup.cs
  
  
  ConfigureServices方法中添加:
  services.AddCors(options =>
            {
                options.AddDefaultPolicy(builder =>
                {
                    builder.WithOrigins("http://localhost:3000") // 允许来自该域名的跨域请求
                        .AllowAnyMethod()
                        .AllowAnyHeader();
                });
            });
     
	Configure方法中添加:
	
    app.UseCors();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

自在猫先生

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

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

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

打赏作者

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

抵扣说明:

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

余额充值