问题描述:Axios无法从asp.net core Web服务获取数据。
解决方法:
services.AddCors(options =>
{
options.AddPolicy("AllowAllOrigins",
builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
然后在Configure方法中使用以下代码启用CORS:
app.UseCors("AllowAllOrigins");
[EnableCors("AllowAllOrigins")]
public class YourController : Controller
{
// ...
}
axios.get('https://your-api-url/api/endpoint')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
请确保替换上述代码中的URL为你的实际API端点的URL。
axios.get('https://your-api-url/api/endpoint', {
headers: {
Authorization: 'Bearer your-jwt-token'
}
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
请确保替换上述代码中的URL为你的实际API端点的URL,并将"your-jwt-token"替换为有效的JWT令牌。
通过上述步骤,你应该能够成功从ASP.NET Core Web服务获取数据。如果问题仍然存在,请检查服务器端和客户端的日志和调试信息,以便进一步排查问题。