Я новичок в ASP.NET Core и React js. Я не могу получить ответ в React от конечной точки контроллера ASP.NET. Весь код на бэкэнде выполняется от начала до возврата строки ответа и получения данных в строке возврата, но в ответе реакции js я не могу видеть данные.
Я старался :
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options =>
{
options.InputFormatters.Add(new BypassFormDataInputFormatter());
options.RespectBrowserAcceptHeader = true;
options.InputFormatters.Add(new BypassFormDataInputFormatter());
options.OutputFormatters.Add(new XmlSerializerOutputFormatter());
}).AddXmlSerializerFormatters().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
это мой передний конец:
getRecordsByPaging = (pagingData) => {
debugger
var jsonData = JSON.stringify(pagingData);
return fetch('/get-products', {
method: 'POST',
body: jsonData,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
}).then(res => {
return res;
}).catch(err => err);
}
это мой бэкенд:
[HttpPost]
[Route("get-products")]
public async Task<IActionResult> GetCustomers([FromBody] req)
{
try
{
if (!ModelState.IsValid)
{
return null;
}
var response = await _productSvc.GetProducts(req);
if (response == null)
{
return null;
}
return Ok(response);
}
catch (Exception e)
{
return null;
}
}
Я не знаю, что делаю неправильно.
Я получаю ответную сторону js:
body: (...)
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: ""
type: "basic"
url: "https://localhost:44384/get-products"
__proto__: Response
Все эти return null;
утверждения нехороши. Вы замалчиваете ошибки.
Вам нужно прочитать фактический ответ на ваш запрос ajax:
getRecordsByPaging = (pagingData) => {
var jsonData = JSON.stringify(pagingData);
return fetch('/get-products', {
method: 'POST',
body: jsonData,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then(r => r.json())
.then(res => {
return res;
}).catch(err => err);
}
Как видите, добавлена строка .then(r => r.json())
, которая на самом деле получит ответ JSON на ваш запрос.
Вы можете узнать больше об API fetch
на странице https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Использование_Fetch.
Базовая выборка:
A basic fetch request is really simple to set up. Have a look at the following code:
fetch('http://example.com/movies.json')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.info(JSON.stringify(myJson));
});
Here we are fetching a JSON file across the network and print it to the console. The simplest use of fetch() takes one argument — the path to the resource you want to fetch — and returns a promise containing the response (a Response object).
This is just an HTTP response of course, not the actual JSON. To extract the JSON body content from the response, we use the json() method (defined on the Body mixin, which is implemented by both the Request and Response objects.)
Эй, друг, большое спасибо за ответ, это работает для меня ....... Ты делаешь мой день .. Еще раз спасибо!
вы отладили? Я думаю, что GetProducts(req); вернуть ноль.