admin管理员组

文章数量:1421750

I've been trying to run a query to a Supabase database that needs a dog breed passed through and will return metrics about it, the breed is defined on the client side. I was able to get the server side query to run but the value is not going through.

+page.svelte

export let metrics;
  export let data;

  const getAllDogs = async () => {
    const { metrics: data } = load({ dog: dog_val });
    metrics = data;
  };
  
  onMount(async () => {
    getAllDogs();
  })


+page.server.js

import supabase from "../../lib/db";

//Method to get all dog breeds
export const load = async ({dog}) => {
  const getAllMetrics = async () => {
    try {
      let { data, error } = await supabase
        .from("dogs")
        .select(
          "avg_size, avg_obedience, avg_passion, avg_health, avg_cleanliness, avg_energy"
        )
        .eq("Breed", dog);
      console.log(data)
      console.log(dog)
      return data;
    } catch (e) {
      console.error(e);
    }
  };
  return {
    metrics: getAllMetrics(dog)
  }
};

I've been trying to run a query to a Supabase database that needs a dog breed passed through and will return metrics about it, the breed is defined on the client side. I was able to get the server side query to run but the value is not going through.

+page.svelte

export let metrics;
  export let data;

  const getAllDogs = async () => {
    const { metrics: data } = load({ dog: dog_val });
    metrics = data;
  };
  
  onMount(async () => {
    getAllDogs();
  })


+page.server.js

import supabase from "../../lib/db";

//Method to get all dog breeds
export const load = async ({dog}) => {
  const getAllMetrics = async () => {
    try {
      let { data, error } = await supabase
        .from("dogs")
        .select(
          "avg_size, avg_obedience, avg_passion, avg_health, avg_cleanliness, avg_energy"
        )
        .eq("Breed", dog);
      console.log(data)
      console.log(dog)
      return data;
    } catch (e) {
      console.error(e);
    }
  };
  return {
    metrics: getAllMetrics(dog)
  }
};
Share Improve this question asked Apr 8, 2023 at 19:56 BeratK2BeratK2 631 silver badge5 bronze badges 1
  • That is not how any of this works, you can't just make up load parameters, nor is that function called explicitly. Please read the docs on loading data, – brunnerh Commented Apr 8, 2023 at 22:04
Add a ment  | 

2 Answers 2

Reset to default 5

The easiest way I know how to do this is to create an api under src->api->dogs->+server.js. Make a call to your database in the API and then in your client you can make a function that will hit your API and return the data. This way you also could update the data using a dropdown or something like that if you do not want to refresh the page.

I have this set up on an onload but normally you would probably call this function with a button or dropdown or some other way of setting breed if you need to somehow set the param "breedToSearch". If you are sending the breed in your URL from your route you can pull it from your url, or if you are trying to set it in the page before you navigate to this page you can use the store to set the value before you navigate and then pull the value from the store when this page loads.

This is just an example of how you would do it using onmount, it's up to you to decide how you want to get your param set before you make the fetch call.

+page.svelte
  //set empty array for dogs if getting array
  let dogs = []
  //set param somehow for breedToSearch
  let breedToSearch = "lab"

  async function getAllDogs {

       const response =  await fetch('/api/dogs?dog=${breedToSearch}', {
                method: 'GET',
            });
        let newData = await response.json();
        dogs = newData.message;

  
  onMount(async () => {
    getAllDogs();
  })


}

+server.js (in the src-api-dogs directory)
/** @type {import('./$types').RequestHandler} */
export async function GET({ url }) {
//get the dog param sent in the fetch call
const dog = url.searchParams.get('dog')

const dogsFromDB = -----call to database----

return new Response(JSON.stringify({ message: dogsFromDB }), { status: 200 })
}

The modern SvelteKit offers some shorthand methods for doing HTTP POST API requests. Depending on the use case use HTTP POST if you are mutating the state on the server, HTTP GET if the request is idempotent query.

In your +page.svelte.js:


  let error = ""; // Render error text in page template if something happens

  // Example function that calls a server-side API from SvelteKit UI code,
  // e.g. on:click handler
  async function myDoSomething(myData) {
        
    const body = {
      param1: myData.something,
      param2: myData.somethingElse,
    };

    try {
      // https://stackoverflow./a/46640744/315168
      console.log("Server-side POST for update", body);
      const resp = await fetch(
        "/api/update-something", 
        {
          method: "POST", 
          body: JSON.stringify(body),
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
          }
        }
      );

      if(resp.status != 200) {
        error = await resp.text()
        console.log("Server error", error);
        throw new Error(`Server problem: ${resp.status} ${resp.statusText}`);
      }
      replyData = await resp.json();
      console.log("Got data", replyData);          
    } catch(e) {
      error = e.toString();
      console.log(e);
    } 
  }  

Then in src/routes/api/update-something/+server.js:

import { json } from '@sveltejs/kit';

export async function POST({ request, cookies  }) {

    const params = await request.json();
    console.log("JSON post params are", params);

    return json({foo: 1, bar: 2}); // Send reply to the client
}   

本文标签: javascriptHow to pass in parameters from client side to server side code in SveltekitStack Overflow