Netlify site: https://smsclockwork.netlify.app/hello-fruit, https://smsclockwork.netlify.app/wow-fruit
Hello everyone,
I’m curious about reading query parameters from incoming requests, so I appended some random query parameters to a URL string. My code at the moment doesn’t do anything with them, but they should still be available nonetheless.
Technically, I have access to the entire URL string by accessing the req.url
property (I’m not sure how it’s accessible either), but I’ll have to write some custom code to parse out each specific parameter. I noticed in the console-logged req
object, there are fields called search
and searchParams
, but they are not immediately available on the req
object; those fields return undefined
.
I tried to use the .json()
method on the req
object, which is a valid method; however, I got the following error: “SyntaxError - Unexpected end of JSON input”.
An interesting observation I noticed is that the context
parameter has the params
object; however, that object was empty even when additional params were appended to the URL string. This made me wonder: in Netlify Serverless Functions, is the standard to use path parameters as opposed to query parameters? I noticed the documentation seemed to only show examples of path parameters
(ex. netlify.app/:fruit/:flavor)
Here is my Netlify Function code snippet:
import type { Config, Context } from "@netlify/functions";
export default async (req: Request, context: Context) => {
const data = await req.json();
console.log('Checking data', data);
const fruitName = Netlify.env.get("FRUIT_NAME");
const optionsObject = { status: 200, statusText: `Hello! My fruit is ${fruitName}` };
return new Response(JSON.stringify(optionsObject));
};
export const config: Config = {
path: ["/hello-fruit", "/wow-fruit"],
};
In summary, my main questions are the following:
- How can I convert the
req: Response
object into a JSON object, if that’s even possible? - Should I be using path parameters instead of query string parameters? Is this a philosophy of Netlify Serverless Functions I’ll have to adopt?
Thank you very much for any help on this matter!