【发布时间】:2020-12-20 05:46:50
【问题描述】:
我正在使用 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);
})
}
而且大部分时候响应都有数据,但是有时候(很难发生),响应数据是一个空字符串,即使服务端有效发送了数据(我知道是因为文本文件记录了要发送的数据) 并且 .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.
【问题讨论】:
-
您的
List_data为空 -
@arslan2012 嗨,List_data 不为空,因为我在转换为 json 字符串之前声明并设置了它(我在上面的评论中指定)
-
所以问题一定出在你设置的时候
-
@arslan2012 不是这样,因为要发送的数据是在Ok返回方法之前注册在文本文件中的,而且这个总是有数据
-
你能把
JsonConvert.SerializeObject(List_data, Formatting.Indented))的结果也放到日志文件里吗?
标签: javascript reactjs asp.net-core axios asp.net-core-webapi