Server-Side Implementation
6.170 Recitation 3
“Single Page App” Design
Database
Web Server
Client
Client
Client
User
User
User
Today’s Example: URL Shortener
Problem: I have a long link like the one for these google slides:�https://docs.google.com/presentation/d/1LR_y6JjAUqco63isfgxWTH1Qo2exH2gRc4Am_BC_GbQ/edit?usp=sharing
Solution: Use a URL shortener like https://goo.gl/�Now I can access the slides by going to https://goo.gl/2YtHNT
A Bit of Design
The key concept of this application is a short. A short allows you to create a (usually shorter, or at least more human-friendly) alias for a URL. If a short exists, anyone can access the URL it points to if they know the name of the short.
Short
User
URL
Name
Created By
Links To
Accessed With
Step 0: Download
Install Node & NPM� Via Package Manager: https://nodejs.org/en/download/package-manager/� Direct Download: https://nodejs.org/en/download/
Check Node version
node -v (should be v10.x.x)
Clone the repository� git clone https://github.com/bamazap/url-shortener� cd url-shortener
Install Dependencies� npm i
Step 1: Try It Out!
Start the app with npm start.
Go to localhost:3000 in your browser.
Create a short linked named google pointing to https://google.com.
Go to localhost:3000/google and see what happens!
Step 2: Examine the Code
app.js | top-level configuration |
routes/index.js | serves the front-end and handles redirects |
routes/shorts.js | handles API requests to create, enumerate, modify, and delete shortened URLs |
Step 3: Inspect Requests
Open web inspector and go to the Network tab.
Create another short and watch the Network tab.
Try creating a short with a name you already used.
Step 4: Send More Requests
Open public/javascripts/services.js.
The addOne function is already implemented. Implement listAll, updateOne, and deleteOne.
Hint: you may need to look at routes/shorts.js to figure out what the right requests to send are.
Step 5: Track Who Created Each Short
Let’s use express-session!� https://www.npmjs.com/package/express-session� npm i -S express-session
Add the session middleware to app.js.
Update the route in routes/users.js to set the user’s username in the session.
Update the routes in routes/shorts.js to use the username from the session to populate the creator property.
Step 6: More Things to Try, or At Least Think About
Restrict edit and delete operations to the creator of the short (if set) only.
Validate URLs. Try entering something that isn’t a link like foo or even google.com and see what happens — do you understand why?
Validate short names. There are some characters you can’t include in URLs — these should not be allowed in short names.
Validate everything. The forms in the GUI take strings, but people can send arbitrary JSON in requests to your API. Is there anything you can put in a request body to break the app? If so, how can you fix it?