Express API
- Look at https://github.com/kurmasz-SampleCode/CIS371-SampleCode/tree/master/JavaScript/blogAPI
- Similar to the
expressMVC example with a few changes
- Port is changed to 3001. (Needs to run on a different port than React server)
bodyParser is JSON instead of urlencoded
- Using
cors package (instead of just adding the header)
- I wrote a single method to automatically create all CRUD routes
- Makes it easier to add more resources later (e.g., blog posts)
- Additional resources take one line. (Or can re-use method in other apps)
- When calling
res.send with objects, they are automatically converted to JSON
AuthorDB.create returns the id of the newly created object
- The
lastID variable is unique to Sqlite3.
- Notice that
this.db.run uses the function syntax, not the () => syntax. This is because the () => syntax won’t set up the this variable properly.
- This is one of the few cases where the difference between
function and () => syntax matters.
More Verbs
- Complete list of HTTP verbs:
- GET
- HEAD
- POST
- PUT
- DELETE
- CONNECT
- OPTIONS
- TRACE
- PATCH
- Typical API verbs
- GET
- POST: Post new data
- PUT: Put replacement data
- PATCH: Patch an entry (i.e., only change part of it.)
- DELETE
- Use
PUT when you are sending the entire object to be replaced.
- This is what
blogAPI does.
- Use
PATCH if you are sending only the fields that are changing.
- Remember, only
GET and POST can be sent directly from a web page.
PUT, PATH, DELETE etc, can only be sent using JavaScript.
Status Codes
- 500 “Internal Server Error.” If you server code crashes. For example:
- Null Pointer Exception
- Divide by Zero error.
- Other unhandled exception.
- (Rails sends a 500 if a DB command fails because you didn’t check that all constraints were satisfied first.)
- 422 “Unprocessable Entry”: Data is well-formed, but invalid. (For example, the Author’s email is not unique)
- 204 “No Content” Used for calls like
update and delete where there isn’t anything else to say but “success”
- Look at
API.jsx.
- Notice that it checks explicitly for status.
- API calls return a promise.
- Anything
returned is passed to the then block.
- If a
throw is called anywhere, the catch block is run.
- See
Authors.jsx in react-blog-complete