010 Fetch API data using Axios - CarrieKroutil/Reactivities GitHub Wiki
Axios is a promise based HTTP client for the browser and node.js - https://github.com/axios/axios. Features advertised:
- Make XMLHttpRequests from the browser
- Make http requests from node.js
- Supports the Promise API
- Intercept request and response
- Transform request and response data
- Cancel requests
- Automatic transforms for JSON data
- 🆕 Automatic data object serialization to multipart/form-data and x-www-form-urlencoded body encodings
- Client side support for protecting against XSRF
To install, cd client-app
to install into the package.json
file by running npm install axios
. If at the root directory by mistake, a new package.json
file and node-modules
folder will get created that would need to be deleted.
import React, { useEffect, useState } from 'react';
import logo from './logo.svg';
import './App.css';
import axios from 'axios';
function App() {
// Hook: useState returns a stateful value, and a function to update it.
// More: https://react.dev/reference/react/useState
const [activities, setActivities] = useState([]);
// Note, the above [] inside useState gives our activities prop a default value of an empty list.
// In order to cause a side effect, when app/component is initiaized, need to tell app what to do when loading up.
// More: https://react.dev/reference/react/useEffect
useEffect(() => {
// All HTTP methods are available through axios.
// The get returns a promise, which we need to tell it what to do by chaining on the "then" method,
// to put the response back from API into activities state variable.
axios.get('http://localhost:5000/api/activities')
.then(response => {
console.log(response);
setActivities(response.data)
})
}, [])
// Note, the above [] empty list dependancy was used to not rerun effect indefinately and only if the list changes.
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<ul>
{activities.map((activity: any) => (
<li key={activity.id}>
{activity.title}
</li>
))}
</ul>
</header>
</div>
);
// Note, because activity is not an interface yet, need to define it as any type to resolve compile errors, beware it is not type safe.
}
export default App;
Check out https://github.com/axios/axios#handling-errors for details on error handling while using Axios.
Just to be aware, you can also use the built-in fetch() method in JavaScript to make HTTP requests, and you can use the setState() method in React to update the state of your application when the response is received.
By combining the Fetch API with React, you can build powerful and dynamic web applications that communicate with APIs and display real-time data to users, just with less features than Axios.
Example:
fetch("http://localhost:5000/api/activities").then(async response => {
console.log(response);
setActivities(await response.json());
Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources on a web page to be accessed from another domain outside the domain from which the first resource was served.
CORS keeps your site safe, and a response header is needed to inform your client app that it is allowed to load data from your API's response object. Learn more here.
Edit \API\Program.cs
to provide CORS configuration by adding a CORS service and some middleware to apply the CORS header to the response going out from API.
CORS Service to add in any location by other services:
builder.Services.AddCors(ops => {
ops.AddPolicy("CorsPolicy", policy => {
policy.WithOrigins(["http://localhost:3000"]).AllowAnyHeader().AllowAnyMethod();
});
});
CORS Middleware to add high in the stack, right before authentication middleware to handle the browser's pre-flight request to see if CORS is available:
app.UseCors("CorsPolicy");
ASP.NET Core apps contain the application startup code in the Program.cs file. The Program.cs file is where:
- Services required by the app are configured.
- ASP.NET Core includes dependency injection (DI) that makes configured services available throughout an app. Services are added to the DI container with WebApplicationBuilder.Services, builder.Services in the preceding code. When the WebApplicationBuilder is instantiated, many framework-provided services are added.
- The app's request handling pipeline is defined as a series of middleware components. Each component:
- Chooses whether to pass the request to the next component in the pipeline.
- Can perform work before and after the next component in the pipeline.
To learn more about ASP.NET Core CORS and set up best practices, check out https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-7.0.
To see the React app talk to the API, make sure to do the following:
- Open a terminal and
cd api
thendotnet run
to start up the API. - Open a terminal and
cd client-app
thennpm start
to launch the app.