Ask Your Question
1

What is the way to incorporate an external backend into SvelteKit?

asked 2023-05-19 20:25:38 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-05-19 20:31:02 +0000

bukephalos gravatar image

To incorporate an external backend into SvelteKit, you can use an HTTP client library like Axios or Fetch API to make requests to the backend server. You can create a "service" module to abstract away the details of making requests and parsing responses, and then import that service into your Svelte components.

Here's an example of what your service module might look like using Axios:

// api.js
import axios from 'axios';

const API_URL = 'https://example.com/api';

export async function getTodos() {
  const response = await axios.get(`${API_URL}/todos`);
  return response.data;
}

export async function createTodo(todo) {
  const response = await axios.post(`${API_URL}/todos`, todo);
  return response.data;
}

// etc.

Then, you can import these functions into your Svelte components and use them like this:

<script>
import { getTodos } from '../api.js';

let todos = [];

async function loadTodos() {
  todos = await getTodos();
}
</script>

<button on:click={loadTodos}>Load Todos</button>

<ul>
  {#each todos as todo}
    <li>{todo.title}</li>
  {/each}
</ul>

Note that this example assumes that your backend API returns data in JSON format. If your API returns data in a different format, you may need to modify the code accordingly.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-19 20:25:38 +0000

Seen: 15 times

Last updated: May 19 '23