realworld icon indicating copy to clipboard operation
realworld copied to clipboard

What is `post` function in `utils.js` for?

Open ulvidamirli opened this issue 3 years ago • 1 comments

I want to know what this function is for and why it is used instead of directly using get or post function from api.js?

export function post(endpoint, data) {
	return fetch(endpoint, {
		method: 'POST',
		credentials: 'include',
		body: JSON.stringify(data || {}),
		headers: {
			'Content-Type': 'application/json'
		}
	}).then((r) => r.json());
}

I can register users by using

const response = await api.post('users', { username, email, password });

instead of

const response = await post(`auth/register`, { username, email, password });

in src/routes/register/index.svelte ->> submit function.

ulvidamirli avatar Sep 11 '21 14:09 ulvidamirli

It is to hide the external API calls. api.js has information about the API (https://api.realworld.io/api). In the real world, this could be a database endpoint with auth tokens that we cannot shared publicly. We don't want to have these info on the client side because the users can just inspect the code on their browser to find the tokens. Instead, we use the post helper to send a request to auth/register, where it calls api.js on the server side without revealing the code to the client.

cocoliliace avatar Sep 06 '22 03:09 cocoliliace