This is what my API call looks like:
export async function getTasks(): Promise<Task[]> {
if (process.env.NODE_ENV === "test") {
return new Promise<Task[]>((resolve) =>
setTimeout(() => resolve(DefaultTasksArray), 1500)
);
} else {
return (await fetch("/api/tasks").then(
(response) => response.json
)) as unknown as Task[];
}
}
GET action in the controller in the API
[HttpGet]
async public Task<IActionResult> Get()
{
var tasks = await _service.GetAsync();
return Ok(tasks);
}
The service in the API
private readonly IMongoCollection<TaskObject> _tasksCollection;
public TaskService(IOptions<TaskManagerDbSettings> taskManagerDbSettings)
{
var mongoClient = new MongoClient(taskManagerDbSettings.Value.ConnectionString);
var mongoDatabase = mongoClient.GetDatabase(taskManagerDbSettings.Value.DatabaseName);
_tasksCollection = mongoDatabase.GetCollection<TaskObject>(taskManagerDbSettings.Value.TasksCollectionName);
}
async public Task<List<TaskObject>> GetAsync() =>
await _tasksCollection.Find(_ => true).ToListAsync();
When I send a GET request in Postman or in a browser, I get a JSON object like:
[
{
*data*
},
{
*data*
},
...
]
But the fetch() returns an empty response. What might be the cause? I don't see any errors in the browser when I open the app.
upd: I see the response in the Network tab in the browser, it has code 200 and all the data. But in the app itself the response is empty.
CodePudding user response:
The json
property on the response from the fetch API is a function which you are mean to call.
(response) => response.json
should be
(response) => response.json()