This is part 9 of Developing Instagram Clone series, other parts are linked below
Disclaimer: I’m a backend developer who learned the front-end for prototyping. So, the code is not well structured and I recommend you follow a better structure, but you’ll get a general understanding of how the front-end service interacts with the back-end services in Microservices architecture
I assume a basic understanding of ReactJS and React Router.
If you can answer the following questions, then you are good to go:
I use only React, React-router and ant design components library.
If you are unable to answer the above questions then I recommend the official react tutorials to start with.
Clone instagram-clone-client project, and let’s have a look into the project structure.
The ApiUtil
The ApiUtil has a very important method “request” which makes a call to an API.
const request = options => {
const headers = new Headers();
if (options.setContentType !== false) {
headers.append("Content-Type", "application/json");
}
if (localStorage.getItem(ACCESS_TOKEN)) {
headers.append(
"Authorization",
"Bearer " + localStorage.getItem(ACCESS_TOKEN)
);
}
const defaults = { headers: headers };
options = Object.assign({}, defaults, options);
return fetch(options.url, options).then(response =>
response.json().then(json => {
if (!response.ok) {
return Promise.reject(json);
}
return json;
})
);
};
It is important to notice at line 8–13, it adds the token to the Authorization header with each request.
Also, ApiUtil has all the method calls to the gateway service.
export function login(loginRequest) {
return request({
url: API_BASE_URL + "/auth/signin",
method: "POST",
body: JSON.stringify(loginRequest)
});
}
login method which makes a post request to “/auth/signin”.
export function getUserProfile(username) {
if (!localStorage.getItem(ACCESS_TOKEN)) {
return Promise.reject("No access token set.");
}
return request({
url: API_BASE_URL + "/auth/users/summary/" + username,
method: "GET"
});
}
getUserProfile, which makes a get request to “/auth/users/summary/{username}” to get a user profile info.
And many other methods which follow the same pattern.
#microservices #react #developer #web-development