我正在使用Asp.net Core 2.2 Web API和ReactJS Axios,但有时(大约100倍中的1倍)响应状态为200,但数据为空字符串。
服务器端控制器代码为:
[Route("api/[controller]")]
[ApiController]
public class SomeApiController : ControllerBase
{
[HttpPost("GetData")]
public IActionResult GetData([FromBody] int id_search)
{
// *Here I get a list data from back using the id_search*
string json = JsonConvert.SerializeObject(List_data, Formatting.Indented));
// *Here I write the json string in a text file, for debbug the data to send*
return Ok(json);
}
}
到目前为止,一切都很好,我在文本文件中编写的json字符串具有如下数据:
[
{
"cod_db": 1,
"nom_db": "Nom1"
},
{
"cod_db": 2,
"nom_db": "Nom2"
}
]
Axios客户端JavaScript代码为(我正在使用axios 0.19.2):
import axios from 'axios';
const clienteAxios = axios.create({
baseURL: 'https://localhost:44364/api/'
}):
export default clienteAxios;
客户端axios方法是:
const getData = () => {
const config = {
headers: {
'Content-Type': 'application/json',
// * The next headers I wrote because i think the problem could be CORS too, but I dont know if are necessary *
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true ,
'Cache-Control': 'no-cache',
'Access-Control-Allow-Headers': 'Content-type, Accept'
}
}
var id_search = 1;
clienteAxios.post('SomeApi/GetData', id_search, config)
.then(d=>{
console.log(d);
})
.catch(d=>{
console.log("error");
console.log(d);
})
}
大多数情况下,响应中都有数据,但是有时(很难发生),即使服务器端有效发送了数据(我知道,因为文本文件记录了要发送的数据),并且.then方法的代码状态为200。
我不知道为什么会这样,但是我怀疑可能是因为CORS。我在Startup.cs存档中有以下cors配置:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
//CORS Activación
services.AddCors(
options => options.AddPolicy("EnableCORS",
builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
.Build();
})
);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
//Enable CORS policy "AllowCors"
app.UseCors("EnableCORS");
app.UseHttpsRedirection();
app.UseMvc();
}
我在做错什么吗,还是有人知道为什么会这样?
编辑:经过多次尝试,我终于设法重新创建了该错误(请记住该错误很难发生)。 Chrome浏览器开发人员工具 “控制台”选项卡什么都不显示,而“网络”选项卡显示:
Headers:
General:
Request URL: https://localhost:44364/api/Login/GetDataBases
Request Method: POST
Status Code: 200
Remote Address: [::1]:44364
Referrer Policy: no-referrer-when-downgrade
Response Headers:
access-control-allow-credentials: true
access-control-allow-origin: *
content-length: 0
content-type: text/plain; charset=utf-8
date: Fri, 04 Sep 2020 10:16:46 GMT
server: Microsoft-IIS/10.0
status: 200
vary: Origin
x-powered-by: ASP.NET
Request Headers:
:authority: localhost:44364
:method: POST
:path: /api/Login/GetDataBases
:scheme: https
accept: application/json, text/plain, */ *
accept-encoding: gzip, deflate, br
accept-language: es-ES,es;q=0.9
access-control-allow-credentials: true
access-control-allow-headers: Content-type, Accept
access-control-allow-origin: *
cache-control: no-cache
content-length: 1
content-type: application/json
origin: http://localhost:3000
referer: http://localhost:3000/
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: cross-site
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36
Request Payload:
1
No properties
Response:
This request has no response data available.
答案 0 :(得分:0)
我怀疑可能是因为CORS。
如您所述,ReactJS客户端发送的大多数请求都可以获取预期的数据,在我看来,问题不是由CORS引起的。
但是同时使用AllowAnyOrigin
和AllowCredentials
方法进行配置是不安全的,因此不建议您使用WithOrigins
方法进行specify the allowed origins。
有时(大约100倍中的1倍)响应状态为200,但数据为空字符串。
根据您的代码,看来您是在本地托管应用程序,以解决问题,可以在操作方法内设置断点,然后调试并跟踪id_search
和List_data
。
此外,如果您将应用程序托管在服务器上,则要解决此问题,您可以尝试write application logs,然后检查应用程序日志以找到有用的信息。
private readonly ILogger _logger;
public SomeApiController(ILogger<SomeApiController> logger)
{
_logger = logger;
}
[HttpPost("GetData")]
public IActionResult GetData([FromBody] int id_search)
{
_logger.LogInformation($"Client passed id_search is '{id_search}'");
//var List_data = YourService.GetDataById(id_search);
if (List_data.Count() < 1)
{
_logger.LogInformation($"Can not get data based on id_search '{id_search}'");
}
string json = JsonConvert.SerializeObject(List_data, Formatting.Indented);
_logger.LogInformation($"Get data based on id_search: {json}");
return Ok(json);
}