1

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

4
  • Where's the problem or what's the question? Commented Feb 23, 2022 at 9:41
  • Hello, I need to receive a json or data that arrives through a post method and that is inside a .svelte component Commented Feb 23, 2022 at 13:59
  • 1
    @SDCOfficeOlimpia Please re-elaborate your question to provide more details. See how to ask. Commented Feb 23, 2022 at 15:22
  • 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... please check this image -> ibb.co/6rJ7qmM Commented Feb 23, 2022 at 15:48

1 Answer 1

2

*.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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.