问题描述
我正在使用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.
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)