I am new to serverless and am trying to get my head around it. So I've created a function on netlify using GET
and it works fine.
Then I wanted a POST
endpoint so I followed the same format and created a similar function. But then I sent a POST
request to this new function. On checking the console.log on the server I realise that it's being read as a request with a GET
method (httpMethod:'GET'). And then I realised that I have not defined the endpoint method which I would have done on a normal server.
But I have no idea how to do that.
Question
Is there a different way to do a GET function and POST function on netlify or serverless?
If the answer is Yes, then please guide me on this.
If the answer is No, and the functions are written in the same way, then can someone advise me why my POST
request is being read as GET
by netlify?
Here's the code from the function on codesandbox .. https://codesandbox.io/s/serverless-function-2xebuf?file=/src/index.js
Posting the answer to this so that it serves as a reminder to me and if it helps someone in the future who has a similar issues
Thanks to @alessiopremoli for sharing that one can't explicitly define to what verb the function handler should respond to .. that answered my first question : Is there a different way to do a GET function and POST function on netlify or serverless?
The second issue that I faced was that my POST request was being read by netlify as GET.. I realised what the issue was.. there's a setting for redirect rules in the netlify.toml file that simplifies the URL to the api.. so you can type "site.com/api/functionName.js" instead of "site.com/.netlify/functions/functionName.js"
[[redirects]]
from = "/*"
to = "/blog/:splat"
and I was using this for my api routes as
[[redirects]]
from="/api/*"
to="/.netlify/functions/:splat"
to simplify the access to my api route.. but I didn't realise that that by default the status code for this redirect is 301 which changes the method to GET
and this was also changing the method of my request. So for those who face this issue, I hope this helps.
If it's a POST request and you are using a redirect option then ensure that you add the status of 200 or just call the function using the default path that you've set eg "site.com/.netlify/functions/functionName.js"
So changing the redirect rule to the one as below fixed the issue for me
[[redirects]]
from="/api/*"
to="/.netlify/functions/:splat"
status=200
Here's the link to the netlify support team that helped resolve this issue that explains it better (https://answers.netlify.com/t/does-using-the-redirects-route-to-a-function-call-change-the-method-of-the-request-from-post-to-get/55760/5)