There seems to be so many choices and I don't have time to read into depth about all of them.
I started using
$.ajax({...})
but now that I use React this is the only place in my app that I use jQuery. I'm basically sending the whole library to the client for this one call.
I then thought about using
window.fetch
However this was not workable because passport does not authenticate this request. I liked it because it was native JavaScript. I don't understand why it is not authenticated by passport code running on my server like the jQuery ajax call was.
I also looked at this library briefly as another way.
github - request
Looks like it might be overkill to make an authenticated ajax request.
Could I just user a native ajax request. Would this be authenticated?
This would be a 4th way - Native Ajax Request - MDN
I normally adopt for native / minimalist solutions even if it means having to write a bit more code.
Passport needs to confirm the session by using cookies but Fetch API doesn't send cookies by default, I think you should add the credentials flag to your request like this:
const options = {
credentials: 'include'
};
fetch(url, options).then(...);
read more about it here: MDN
Related
I am building a react web app that needs to pull data from the Gravity Forms API. Someone has set up the Consumer_Key and Secret_key for me and I have it working fine in Postman.
I have not used OAuth with an API call in Javascript before and am struggling to find a way to implement it. As I understand it, the call first needs to send my keys, then it recieves a 'nonce' and timestamp, then it needs to send the call again with all these things added and then I get my result.
I've poured through the Axios docs, as well as the Gravity Forms docs (https://docs.gravityforms.com/rest-api-v2-authentication/) and done plenty of Goggling but am so far drawing a blank. I've seen suggestions of using an interceptor with Axios but that answer was downvoted to 0 on here. Also I have come across some specific OAuth node libraries but I am not sure if a Node library is what I want for a front-end (React) call.
This is what I send in Postman:
And this is the response I get:
Looking through the Axios requests that Postman generates after a successful call I've noticed this pattern in the URL:
const apiString = ${API_URL}${API_FIELDS}&oauth_consumer_key=${CONSUMER_KEY}&oauth_signature_method=HMAC-SHA1&&oauth_timestamp=${oauthTimeStamp}&oauth_nonce=${oauthNonce}&oauth_version=1.0&oauth_signature=${oauthSignature};
I already have the variables in capitals so I guess I need to find a way of generating the ones in camelCase and then building my URL?
Alternatively does anyone have an up to date guide of how to implement this API call using just Axios or Fetch?
I have the following problem: I want to change one variable on a page. The input comes from another page so:
I'm using Node.js, Express.js and Ejs for this task.
Server - storing the values
Index page - Control page with input fields and send button
Display page - Shows the variable
I'm sending the variable with fetch post to the server. On the server I change the variable with the request body value and when I reload the "Display page" manually I see the new value. The problem is: I need to change it without any manual refresh or other things, because that won't be possible.
There is the possibility with "location.reload()" to refresh it every X second. But that's not the way I want to use, I really just want to refresh it when the variable changes. Is there a function (from express.js for example) I can use for it?
edit: I should mention that this project would be just used in our network and its not open for other users. Like an in-house company dashboard kind of.
So a "quick and dirty" solution can work too, but I want to learn something and wanted to do it the right way though.
This is a very common scenario that has several solutions:
Polling - The display page runs ajax calls in a loop every N seconds asking the server for the lastest version of the variable. This is simple to implement, is very common, and perfectly acceptable. However, it is a little outdated, and there are more modern and efficient methods. I suggest you try this first, and move on to others only as needed.
WebSockets - WebSockets maintain a connection between the client and server. This allows the server to send messages to the client application if/when needed. These are a little more complex to setup than just plain ajax calls, but if you have a lot of messages getting sent back and forth they are much more efficient.
WebRTC - This is taking it to another level, and is certainly overkill for your use case. WebRTC allows direct messaging between clients. It is more complicated to configure than WebSockets and is primarily intended for streaming audio or video between clients. It can however send simple text messages as well. Technically, if you want to persist the message on the server, then this is not suitable at all, but it's worth a mention to give a complete picture of what's available.
The simplest solution that came to mind is to have the server return the updated post in the body, then use that to update the page.
You can also read about long/short polling and Websockets.
One possible solution would be to add page reload code after a successful post-operation with fetch.
fetch(url, {
method: 'post',
body: body
}).then(function(response) {
return response.json();
}).then((data) => {
// refresh page here
window.location.replace(url);
});
Proper solution (WebSockets):
Add WebSocket server as a part of your Node.JS app
Implement subscriptions for the WebSocket, implement function 'state changed'.
subscribe on a method 'state changed' from your client browser app.
call ws server from your express app to update the clients when your variable is changed
Outdated (Polling):
Add express endpoint route: 'variable-state' Call server from your
client every n ms and check whether variable state is changed.
Refresh the page if variable is changed.
I'm using node.js with the express.js framework and EJS to handle the templates.
Here's my route:
app.get('/',function(req,res) {
res.render('index', {
matches: [],
status_message: '',
message: ''
});
});
When I call app.post, I run queries to a database updating variables 'matches' and 'status_message'. How would I update these variables rendered in the page without having the page reload.
For example, if the user provides invalid credentials, I'd like update the 'status_message' to "Invalid Credentials".
Use AJAX.
Basically, modern browsers implement a class called XMLHttpRequest that can make HTTP requests to HTTP servers. In your client-side Javascript, create an XMLHttpRequest object and use it to execute the post request to your server. Use the same XMLHTTPRequest object to listen for the server response, then do whatever you want with the response, such as updating a div.
You tagged this question with ajax so I guess you already know about it, but you didn't mention or ask anything about it in your question. There are tons of examples of this kind of thing online, e.g. here that you can try. There's also jQuery.ajax() which you might find easier to use than native AJAX.
In my previous angularjs project I used interceptors to intercept the http calls, and to be able to serve mock data instead of the real data from the server. I found it very useful throughout the development process.
My question is, how could I do this without angularjs (In my current project I use another framework, which does not have interceptors)?
Is there any other http library out there, that supports this? How could I achive this using jquery's or superagent's http capabilities?
So i found the following script: https://github.com/creotiv/AJAX-calls-intercepter/blob/master/index.html
Here is a live fiddle: http://jsfiddle.net/0eyadb88/1/
I'm not going to go over everything in the script as simply it looks like it does handle the XMLHttpRequest as i commented on. To what extent this works, well that would be just some testing of course and should be able to be expanded.
i've added a non jquery ajax call (testing with chrome here) and it handles that as well.
The main section to pay attention to is
(function (open) {
XMLHttpRequest.prototype.open = function (method, url, async, user, pass) {
alert('Intercept');
open.call(this, method, url + ".ua", async, user, pass);
};
})(XMLHttpRequest.prototype.open);
Personally i would use this approach unless a decent libary is around, but of course if such a libary exists. please do let us know ;)
Otherwise cleaning up the script or using that one in general should be fairly easy.
You should check out dfournier/plasticine. I developed this library in order to intercept a request and fake the response or intercept server response and modify it. I use it at work and the backend team is not ready but we already defined the API.
I'm trying to do a get request via javascript/jquery to attain all of my workspace IDs in asana. I know when I just put the URL in the browser, asana returns all of my workspace IDs. However, when I do a GET request of the same URL, I'm getting a 401 error (Not Authorized).
How do i fix this? I know after I do a login through OAuth I am provided a token, am I supposed to do something with that?
$.get("https://app.asana.com/api/1.0/workspaces", function(data){
alert("Data: " + data);
});
Also, please do not tell me to do it on the server side instead. I'm doing a simple web application and I'm doing it with javascript/jquery. That is not an answer. Thank you.
You need to authenticate your request, either using OAuth or the API Key. If you're developing an application for others to use, and you want them to be able to access their Asana data, you probably want to use OAuth - if it's just for a script you run for yourself, your API Key should be fine.
Generally speaking, OAuth has enough nuances that if you're using it (and not intimately familiar with it), we'd recommend using a library of some kind. If you're using jQuery, perhaps https://gist.github.com/andyedinborough/1012960 would help? (Caveat: I haven't tried it myself)
The short version of OAuth is that you need to get a token, which you can then pass to the API in the form of an HTTP header of the form Authorization: Bearer $TOKEN. It sounds like you already have a token, so you just need to add the header and it should work. And yet, GET is the correct verb to use here.