我编写了一个demo使用react中的axois请求后端中的接口并返回json数据,这个后端接口我在使用postman今天调试的时候是ok的,把这个后端地址放在地址栏中也是ok,就是在使用react进行调用的时候异常了,好像存在跨域的问题。
前端代码
const generateDoc = async () => {
try {
const response = await axios.post(''http://接口地址/Home/Index'');
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);
// 在此处根据实际情况进行相应的错误处理,例如提示用户重试等。
}
};
后端代码
public ActionResult Index()
{
var data = new
{
Name = "John",
Age = 30,
Gender = "Male",
Address = new
{
City = "New York",
Country = "USA"
}
};
return Ok(data);
}
Startup.cs
// 添加跨域服务
services.AddCors(options =>
{
options.AddPolicy("localhost", builder =>
{
builder
// 允许所有来源
.AllowAnyOrigin()
.SetIsOriginAllowedToAllowWildcardSubdomains()
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
postman请求
根据您的描述和截图
根据您的描述,这里存在跨域问题,导致前端无法调用后端API。可以在Startup.cs中添加CORS服务端中间件来解决这个问题。具体步骤如下:1. 安装Microsoft.AspNetCore.Cors包:
Install-Package Microsoft.AspNetCore.Cors
csharp
services.AddCors();
csharp
app.UseCors(builder => builder
.AllowAnyOrigin() // 允许所有来源
.AllowAnyMethod() // 允许所有方法
.AllowAnyHeader() // 允许所有标头
);
csharp
[EnableCors]
public class HomeController : Controller
{
...
}
js
axios.post('http://地址/Home/Index', {
credentials: true // 标记这是一个跨域请求
})
这样,后端通过CORS中间件就会响应这个 OPTIONS 预检请求,返回允许跨域的头信息。前端得到响应后就可以正常发出实际的 POST 请求了。