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)
For my experience, you can't explicitly define to what verb the function handler should respond to, I usually set a check on the event verb:
if (event.httpMethod !== 'POST') {
return {
statusCode: 501,
body: JSON.stringify({ message: "Not Implemented" }),
headers: { 'content-type': 'application/json' }
}
Related
I'm implementing social login on my website.
I was able to implement the "One tap" flow, but I need to have an alternative to handle the "cooldown" which prevents the popup from appearing, if the user blocked it or closed it.
So I followed the "Authorization" flow on Google documentation.
Until yesterday morning everything was working fine and I succesfully exchanged the code with a token by calling
https://oauth2.googleapis.com/token
or
https://accounts.google.com/o/oauth2/token
sending secret and everything.
In a first instance I used Postman, then I made a sample code in a Spring project, before preparing the final code in another Spring project.
The first run in the final project I started getting a 400 error, with the redirect_uri_mismatch error key.
And then I was never able to do the exchange anymore, I get the same error from Postman as well.
The config is correct (It never changed from when it was working).
How can I solve this??
Here's some code
FRONTEND
this.client = google.accounts.oauth2.initCodeClient({
client_id: this.clientId,
scope: "openid profile email",
ux_mode: "popup",
redirect_uri: this.redirectUri,
callback: (response) => {
debugger;
this.submitFakeForm({
clientId: this.clientId,
code: response.code
});
}
});
this.client.requestCode();
POSTMAN PARAMS
this.redirectUri is identical to the one passed here and set up on Google credentials
FOR THE MOST SKEPTICAL, THE AUTHORIZED REDIRECTS :)
They're repeated in couples, because one is for local development, one is for the integration environment.
And of course the production config is on another credential.
Nowhere in the docs is this, but I came across this answer here on stackoverflow and it's basically suggesting not to pass the real redirect_uri, but to use a fixed string postmessage.
I want to point up again that I was using the real redirect_uri yesterday and it worked.
I will do some tests again in the future and update here if something changes.
For now just know that using postmessage fixed the issue for me
also I will be using https://oauth2.googleapis.com/token as endpoint, since it's the one mentioned in the (awful) docs, although https://accounts.google.com/o/oauth2/token works just as well.
I am using MSGraph API in Javascript to read and update Sharepoint lists, I am successfully retrieving data, but every time I try to update a value using a PATCH call, I get:
The URL is:
Here is the request headers/payload/response headers:
The strange thing is when I try this on MS Graph Explorer it works, and the request headers and payload are identical.
Any ideas what is wrong?
Here is a snapshot of the code I am using:
So the resolution to this issue was to create a new app registration in azure portal, it was set up with the same permissions as the one that didn't work, so not sure how it fixed it, but it did.
I'm building a ReactJS app on top of a WordPress backend. The React App is running on the same domain, embedded in the WordPress site. Most of the tutorials I've been following cover how to get data from WordPress to React. I've been successful at this, but need to figure out how to submit data from my React app to WordPress (preferably via the REST API).
This will be a custom admin page for logged in editors, either available in the admin panel or from the front-end.
As an example to create a post, I'm naively trying the following function:
saveGrid() {
const url = "/wp-json/wp/v2/posts";
const body = JSON.stringify({
"title":"internet",
"content":"teapot"
});
fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body:body
});
}
I get back a 401 unauthorized response. What is the easiest way to authorize myself for a POST submission (secure solution preferred)?
It looks like you're on the right track.
A quick read of this: https://apppresser.com/wp-api-post-submission/
shows me that all you're missing is a "nonce" in order for the WP API to recognise and validate your request successfully.
In the guide above, the dev created a JS written in JQuery that sends XHR/AJAX requests to the WP API and in their plugin.php they enqueue and localize the script with some variables from WP to help with the request inside the JS.
The takeaway here is that they used wp_create_nonce('wp_rest')and assigned this to a localized variable nonce so they could easily reference that later inside the JS and assign nonce to their X-WP-Nonce header inside the request!
If you look into this further you might find a suitable alternative for you that will work as I'm not entirely sure how you're loading your JSX files but this guide may come in handy for you to enqueue your JSX scripts/files: http://blog.milandinic.com/2015/12/01/using-react-jsx-in-wordpress/
More information
https://codex.wordpress.org/Function_Reference/wp_localize_script
https://developer.wordpress.org/reference/functions/wp_enqueue_script/
I was able to solve this problem by, instead of having a straight post request from React, using a Jquery AJAX submission outside of React that uses data from a form inside React. This caused the request to contain the necessary cookies (I don't understand exactly why this is the case)
I've seen a few people having problems with the oAuth1.0 using hello.js with Twitter, LinkedIn etc. Unfortunately, I am one of them. Trying everything I can to fix it, but I need help.
To explain:
I have my Twitter credentials initialised:
hello.init({
'twitter' : '*******************'
},
{
redirect_uri:'****************',
oauth_proxy: 'https://auth-server.herokuapp.com/proxy'
});
(I presume that the 'oauth_proxy' in my case here is correct?)
Apart from that, I have tried calling the function in the button tag like so:
onclick="hello.login('twitter');">
I have seen people making errors having skipped the 'https://auth-server.herokuapp.com/#signin' step but I have all my credentials inputted there for the mean time. But, one question:
The 'Reference' section, is that just a nickname kind of thing? And what's the 'Domain' section about?
The error that I'm receiving is a 401 error message.
Another question:
Do I need all of the 'twitter.js' & 'client_id.js', or is including 'hello.js' sufficient?
I appreciate any effort to help me with this. Thank you.
As Andrew said (after all, he is the one who wrote hello.js), one of the problems could be related to the callback URL. I found out after a while that Twitter (unlike Facebook) does not accept 'localhost', so instead one has to write 127.0.0.1.
That solved all my problem when being stuck at the same point.
So yes, the reference is a nickname e.g. "dropbox", and the domain field is the domains e.g. "myapp.com". Its advised to fill both these in for your own reference and their misconfiguration wont lead to a 401.
The 401 is likely that your client id / secret is incorrect. Or the redirect_uri defined in hello.init does not match the Callback URL you assigned to that client id when you registered with a third party service.
The error handler hello(network).login().then(successHandler, errorHandler) should give more information. Can you attach that too your question?
"client_id.js" is a demo script which defines the credentials used for my hellojs demos. Do not include it!
However you may like this approach for maintaining your application credentials in a separate file - this approach is left up to you.
All you need to include to get started is dist/hello.all.js this contains hello js and all the third party configurations listed.
Due to circumstances beyond my control, Javascript is the only language option available for me. I'm a beginner and am not even sure if I'm approaching the problem in a "recommended" manner.
Simply put, a customer has setup a MarkLogicDB server online and has given me read-only access. I can query the server with the HTTP GET protocol to return an XML document that has to be parsed. I've been able to create a curl command to return the data I need (example below);
curl --anyauth --user USERNAME:PASSWORD \
-X GET \
http://test.com:8020/v1/documents?uri=/path/to/file.xml
The above returns the requested XML file. Can someone please show me how I could convert the above to javascript code? Additionally, how would I parse the data? Let's say I want to get all the info from a certain element or attribute. How can this be accomplished?
This would be trivial for me to do in Java/.NET, but after reading plenty of online tutorials on Javascript, my head is spinning. Every tutorial talks about web-browsers, but I'm doing this on a server environment (The parse.com CloudCode). There isn't any UI or HTML involved. For debugging, I just read the logs created with console.log().
https://parse.com/docs/cloud_code_guide#networking seems pretty clear, as far as it goes.
Parse.Cloud.httpRequest({
url: 'http://test.com:8020/v1/documents',
params: {
uri : '/path/to/file.xml'
},
success: function(httpResponse) {
console.log(httpResponse.text);
},
error: function(httpResponse) {
console.error('Request failed with response code ' + httpResponse.status);
}
});
But you'll also need authentication. The Parse.Cloud.httpRequest docs don't include any examples for that. If you have support with that vendor, ask the vendor about digest authentication.
If you're stuck you might try adding user and password to the httpRequest params and see what happens. It might work, if the developers of this stack followed the XMLHttpRequest convention.
Failing support from the vendor and existing functionality, you'll have to implement authentication yourself, in JavaScript. This works by generating strings that go into the request headers. These resources should help:
http://en.wikipedia.org/wiki/Digest_access_authentication
http://en.wikipedia.org/wiki/Basic_access_authentication
Basic auth is much easier to implement, but I'd recommend using digest for security reasons. If your HTTPServer doesn't support that, try to get the configuration changed.