I havebeen having trouble with backend for a while now and Express JS has made it especially hard. However, I think I am to blame, because I've been going at with the approach that it was an MVC framework generator or maybe it was a framework that helps with authentication. But if I am correct, Express JS should reflect a RESTful API for everything. Not just for user sign up (POST) and loggin in (GET).
This is where I am kinda need clarification. From now on, is it best practice to always use RESTful API when interacting with a database? A real issue I had was with a user table and a likes table.
If a user clicks a like button on a photo, I want to do something like:
INSERT INTO likes (user_id, photo_url) VALUES (current_user, url);
What would the approach be to do this? How do I tell the like button to refer to the API? It's not like a signup form, where we give them names. Or do I just go into the Express file and start defining routes?
Yes, you create an express route for each ajax call that you wish the client to be able to make.
Here's the general sequence of events for a Like button on a photo:
User logs in. That creates some sort of state in the cookie that identifies the user (either an ID or more likely a server-side session).
User presses Like button on a photo.
Javascript attached to the Like button in the browser, gets the current photo ID and makes an Ajax call for "likePhoto" with the current photo ID as a parameter for the Ajax call.
The Ajax call hits an Express route that you have previously set up to handle this Ajax call.
If there is no logged in user session associated with this request, then the request is probably denied (probably returns some error code associated with unauthorized).
The Express route uses the cookie to identify the user making the request so it now has the photo ID and the user so it can make the database call to add the Like to the DB.
After the DB operation completes, the ajax call can return a 200 status and whatever response is appropriate.
Related
I am having a very hard time understanding the exact process of "post/redirect/get".
I have combed through this site and the web for several hours and cannot find anything other than "here's the concept".
How to understand the post/redirect/get pattern?
Wikipedia explains this so well!
The Problem
The Solution
As you may know from your research, POST-redirect-GET looks like this:
The client gets a page with a form.
The form POSTs to the server.
The server performs the action, and then redirects to another page.
The client follows the redirect.
For example, say we have this structure of the website:
/posts (shows a list of posts and a link to "add post")
/<id> (view a particular post)
/create (if requested with the GET method, returns a form posting to itself; if it's a POST request, creates the post and redirects to the /<id> endpoint)
/posts itself isn't really relevant to this particular pattern, so I'll leave it out.
/posts/<id> might be implemented like this:
Find the post with that ID in the database.
Render a template with the content of that post.
/posts/create might be implemented like this:
If the request is a GET request:
Show an empty form with the target set to itself and the method set to POST.
If the request is a POST request:
Validate the fields.
If there are invalid fields, show the form again with errors indicated.
Otherwise, if all fields are valid:
Add the post to the database.
Redirect to /posts/<id> (where <id> is returned from the call to the database)
I'll try explaining it. Maybe the different perspective does the trick for you.
With PRG the browser ends up making two requests. The first request is a POST request and is typically used to modify data. The server responds with a Location header in the response and no HTML in the body. This causes the browser to be redirected to a new URL. The browser then makes a GET request to the new URL which responds with HTML content which the browser renders.
I'll try to explain why PRG should be used. The GET method is never supposed to modify data. When a user clicks a link the browser or proxy server may return a cached response and not send the request to the server; this means the data wasn't modified when you wanted it to be modified. Also, a POST request shouldn't be used to return data because if the user wants to just get a fresh copy of the data they're forced to re-execute the request which will make the server modify the data again. This is why the browser will give you that vague dialog asking you if you are sure you want to re-send the request and possibly modify data a second time or send an e-mail a second time.
PRG is a combination of POST and GET that uses each for what they are intended to be used for.
Just so people can see a code example (this is using express):
app.post('/data', function(req, res) {
data = req.body; //do stuff with data
res.redirect('public/db.html');
});
So to clarify, it instantly refreshes the webpage and so on refresh of that webpage (e.g. if you updated an element on it) it won't repost the form data.
My code used to look like this:
app.post('/data', function(req, res) {
data = req.body;
res.sendFile('public/db.html');
});
So here the response is sending the html file at the /data address. So in the address bar, after pressing the submit button it would say for me: localhost:8080/data.
But this means that on refresh of that page, if you have just submitted the form, it will submit it again. And you don't want the same form submitted twice in your database. So redirecting it to the webpage (res.redirect) instead of sending the file (res.sendFile) , stops the resubmission of that form.
It is all a matter of concept, there is no much more to understand :
POST is for the client to send data to the server
GET is for the client to request data from the server
So, conceptually, there is no sense for the server to answer with a resource data on a POST request, that's why there is a redirection to the (usually) same resource that has been created/updated. So, if POST is successful, the server opiniates that the client would want to fetch the fresh data, thus informing it to make a GET on it.
I need to show all server side REST actions on angular js UI in my application.
Like when the user is created, I need to show User is created/failed immediately on the panel on GUI.
I am saving all such actions in DB table(Recent Activity).I need to fetch data from DB table and show it on UI.
One way to design it get latest data from DB table(Recent Activity) on every action on the UI but for that, I need to make REST call on each action which is not very maintainable code.
What is the best way to design/implement above problem in angular js?
P.S. Application backend is implemented in Springboot
When you will create a user, you are going to hit a create User API and that API will return HTTP response.
So you can check if you get a success, just notify user a success message else failure message.
Hope this helps!
When a user scans QR code in our web page and makes purchase with it (using a 3rd party application), I want to hide that QR code and process the purchase.
I got an API to check whether the transaction was successful or not. My first thought was sending a request to that API every 2 seconds to check the transaction (terrible idea?). But they told us to create something called a "hook" and they would subscribe to it. What's that? How should I implement that?
Hook may generally mean webhook, here is the wikipedia description.
Webhooks are "user-defined HTTP callbacks". They are usually triggered
by some event, such as pushing code to a repository or a comment being
posted to a blog. When that event occurs, the source site makes an
HTTP request to the URI configured for the webhook.
Hook/Webhook
Think a hook as an endpoint, where a user can notify you / giving you information.
The way it work is like a user accessing a url and sending params
your-url.com/hook?order_id=123&status=complete
Warning: Example code, generally a good hook should provide authentication method.
That way your server can interpret that information as
order with id 123 has been completed
That was a basic implementation.
Other easier analogy is:
a user accessing a url and input a form and press submit. To which url the data is sent, that url can also be called hook.
Basically they are telling you to implement a service that they would call when a transaction ocurred successfully, instead of you going to them.
Since mostly a backend guy, I am not sure how can I achieve the following since it
requires some interaction with the browser.
So, I have a the following things so far.
A communication protocol where server is in python and client is in javascript code.
Ultimately, I want my data to reach to that javascript code.
Now, this data is being captured from browser.
As a practice.. what I am trying to do is.. have two radio buttons on my browser and a submit button
*radio A
*radio B
* Submit
Now, when the user presses submit, I somehow want to create a query "user submitted: A (or B)" and this query i am able to capture on python script.
I am at lost on how to do this.
My guess is that "submit" invokes a python script.
But what if my python server is always on .. how do i parse that response from the click of browser to this python server?
This is the way it usually works:
Client (browser) visits webpage and initiates request to server
Server (in your case, Python) handles request and writes HTML response, including the radio-button form
Client fills out form and hits Submit, triggering another request to the server
Server handles the second request and writes another response (e.g. "Purchase successful", "message posted", etc.).
Note that the second request is a brand-new request. You may want some way of linking the first request to the second one unless the second request is anonymous. Some frameworks will do that for you, but if you are making the server from the ground up you'll want some kind of session mechanism to keep track of state.
To get the client to make the second request, the simplest is to add appropriate action and method attributes to the form element in your HTML. action specifies the URL to access for the form request, and method is either GET or POST. (More advanced usage, e.g. on this site, typically uses AJAX to make the submissions instead).
I want to add authentication to existing application that uses Ajax and I am thinking of the best way to do it.
Here is a typical scenario:
First request - ask for a login, proceed to the first screen. This works well.
Session expired.
Since I do ajax and send 2 requests per action (one actual request and one that records the action for statistics/audit) it could happen on one of those. When it happens the app shows me the authentication screen and after successful authentication user is forwarded to the previous request.
The problem here is that I don't want a forward, I want my custom Ajax/javascript handling to get the response and handle it. Is it possible to just pop up a window to authenticate, then when I get the response continue like the session never expired?
I have this in the web.xml :
<login-config>
<auth-method>FORM</auth-method>
<form-login-config>
<form-login-page>/jsp/login.jsp</form-login-page>
<form-error-page>/jsp/login_error.jsp</form-error-page>
</form-login-config>
</login-config>