繁体   English   中英

Axios response get 200 code 状态,但有时数据为空

[英]Axios response get 200 code status, but sometimes data is empty

我使用的是 Asp.net Core 2.2 Web API 和 ReactJS Axios,但有时(大约 100 次中有 1 次)响应状态为 200,但数据为空字符串。

服务器端Controller代码为:

[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);
        })
}    

大多数时候响应都有数据,但有时(很难发生) ,响应数据是一个空字符串,即使服务器端有效地发送了数据(我知道是因为文本文件记录了要发送的数据)和the.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.

我怀疑这可能是因为 CORS。

正如您所说,ReactJS 客户端发送的大多数请求都可以获得预期数据,在我看来,问题不会由 CORS 引起。

但是同时使用AllowAnyOriginAllowCredentials方法进行配置是不安全的,不推荐使用,您可以使用WithOrigins方法指定允许的来源

有时(大约 100 次中有 1 次)响应状态为 200,但数据为空字符串。

根据您的代码,您似乎在本地托管应用程序,要解决此问题,您可以在操作方法中设置断点,然后调试和跟踪id_searchList_data

此外,如果您的应用程序托管在服务器上,要解决问题,您可以尝试编写应用程序日志,然后检查应用程序日志以找到有用的信息。

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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM