我编写了一个React18.2版本调用后端.net core接口生成word文档的功能。
我遇到了一个问题,就是当我前端传递数据有多行的时候,会请求不到这个后端的接口会抛出异常:500
前端数据格式:
我的前端数据格式是这样的
[{…}, {…}, {…}]
0: {id: '0', en_name: 'id_en', zh_name: 'id_users', type: 'int', length: 11, …}
1: {id: '1', en_name: 'Username', zh_name: '用户名', type: 'varchar', length: 50, …}
2: {id: '2', en_name: 'Password', zh_name: '密码', type: 'varchar', length: 255, …}
前端方法
const generateDoc = async () => {
// 将 selectedRows 转换为需要的格式
const documents = selectedRows.map(row => ({
id: row.key,
en_name: row.en_name,
zh_name: row.zh_name,
type: row.type,
length: row.length,
editable: row.editable,
visible: row.visible,
enabled: row.enabled
}));
const options = {
method: 'POST',
url: '/Home/GenerateDocument', // 使用代理前缀路径
responseType: 'arraybuffer',
headers: {
'Content-Type': 'application/json'
},
data: JSON.stringify(
documents
)
};
console.log("前端传递数据:",documents);
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 = 'MySolution.docx';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
} catch (error) {
console.error(error);
}
};
后端接口
[HttpPost]
public async Task<IActionResult> GenerateDocumentAsync([FromBody] List<Document> documents)
{
try
{
_logger.LogInformation($"Received document: {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);
}
}
是不是因为后端是一个集合导致的,我前端传递的时一个数组对象
postman请求异常
postman请求成功
postman传数组多个元素没问题的话,改变编码中的数据结构试试!