Coding Warmup: Async Functions
- Yesterday we fetched data using asynchronous functions and get requests.
- Let’s build on this by enhancing and optimizing our brute force code
- Codepen Starter Code
Step 1: Code Walkthrough
- note where code could be enhanced (make it versatile)
- note where the code could be DRYer (make it reusable)
- note where there should be error handling
Step 2: Optimization
- break up functions so they are more evenly scoped
- add arguments
- test to make sure you can pass different information
Step 3: Clean it up
- Add error handling
- Get rid of unnecessary code
- Get rid of unnecessary comments
- Update naming conventions as necessary
A Simple Node HTTP Server
Basic Syntax:
const http = require("http");
const hostname = "127.0.0.1";
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader("Content-Type", "text/plain");
res.end("Hello, World!\n");
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
Activity: Serve an HTML file using a node http server
- Follow the instructions on this page
- it demonstrates also how to use csv data, json data, and js data. however for this we’ll focus on servering a simple html file
- this is basically what the live server plugin is doing behind the scenes when you were making sites in cpnt-260
Node Express (a very abbreviated intro)
- Express puts the E in MERN, MEVN, and MEAN stacks (react, vue, and angular respectively)
- It is a server micro library
- Modern frameworks like Sveltekit, NextJS, and NuxtJS support server side routes
- However you may work on projects that have a separate backend (or you might just really like backend development)
- A standalone backend will give you more control over ports and how everything works, but it’s much more challenging to configure and get working
Server API Routes in Nuxt
- Documentation
- in
./server/api/
add .js files for your various api calls.- you can do this for data you are hosting as well
- then in your vue files, fetch the data with the
useFetch()
composable functionconst { data } = await useFetch('/api/hello'
- you might need to work with the data in your script tags. however if the logic needed to edit the data to make it easy to render gets too complex, or if it could be reused - move it to the
composables/
directory.
Activity: fetch from the disney api in Nuxt
- use the logic that we made in codepen
- start simple, get just basic data to log
- then pass that data to a vue file
- then render it using the appropriate template syntax