Home > Blockchain >  Create a svelte component with a function recive a data by post
Create a svelte component with a function recive a data by post

Time:02-27

I need to expose a .svelte component that receives data through the post method, so that an external service can consume it and that the received data can be displayed as received

// test.svelte

<script>

let name="";
let age="";
let gender ="";

export async function post({request}){
       const body = await request.json();
       console.log(body);
       name = body.name;
       age = body.age;
       gender = body.gender;
       return {
             body:JSON.stringify({body})
       } 
    });

</script>
<form>
    <div>
       <p>{name} {age} {gender}</p>
    </div>
</form>

Check this picture maybe understand better

CodePudding user response:

*.svelte files don't handle POST request directly.

The code you've written doesn't work inside the <script> tag of a Svelte component. Post data is not available in the frontend.

However if you're using a up-to-date SvelteKit and are hosting a non-static version.
(By using the @sveltejs/adapter-node for example)

You can use the Shadow Endpoint feature:

<!-- src/routes/test.svelte -->
<script>
export let name;
</script>

<h1>{name}</h1>
// src/routes/test.js
export async function post({ request }) {
  const data = await request.json();
  return {
    body: {
      name: data.name
    } 
  }
};

When you create an endpoint with the same filename, the post request is handled by the endpoint (backend) and if the request contains an Accept: text/html or Accept: */* header the server will respond with the SSR page using the values from the body as props.

  • Related