完美实现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();