Import of glitchdotcom/glitch-hello-node

This commit is contained in:
Glitch (glitch-hello-node) committed 2021-05-26 21:54:31 +00:00
1 parent 180d799c09
commit 6fd4e86a6d
4 files changed
+98 -31

No files matched your search

+29 -8
View File
@@ -1,25 +1,46 @@
# Hello Node
# Hello Node!
[Node.js](https://nodejs.org/en/about/) is a popular runtime that lets you run JavaScript on the server instead of in a browser. This project uses the [Fastify](https://www.fastify.io/) framework to explore basic templating with [Handlebars](https://handlebarsjs.com/) and submitting data using forms and querystrings.
This project includes a Node.js server script and a web page that connects to it. The front-end page presents a form the visitor can use to submit a color name, sending the submitted value to the back-end API running on the server. The server returns info to the page that allows it to update the display with the chosen color. 🎨
[Node.js](https://nodejs.org/en/about/) is a popular runtime that lets you run server-side JavaScript. This project uses the [Fastify](https://www.fastify.io/) framework and explores basic templating with [Handlebars](https://handlebarsjs.com/).
## What's in this project?
← `README.md`: That’s this file, where you can tell people what your cool website does and how you built it.
← `public/style.css`: The styling rules for your pages and posts.
← `public/style.css`: The styling rules for the pages in your site.
← `server.js`: The main server script for your new site.
← `server.js`: The **Node.js** server script for your new site. The JavaScript defines the endpoints in the site back-end, one to return the homepage and one to update with the submitted color. Each one sends data to a Handlebars template which builds these parameter values into the web page the visitor sees.
← `src/`: This folder holds the main template for your site along with some basic data files.
← `package.json`: The NPM packages for your project's dependencies.
### Working in the `src/` folder 📁
← `src/`: This folder holds the site template along with some basic data files.
← `src/pages/index.hbs`: This is the main page template for your site.
← `src/pages/index.hbs`: This is the main page template for your site. The template receives parameters from the server script, which it includes in the page HTML. The page sends the user submitted color value in the body of a request, or as a query parameter to choose a random color.
← `src/colors.json`: A collection of CSS color names. We use this to pick a random color, and to match searches against color names.
← `src/colors.json`: A collection of CSS color names. We use this in the server script to pick a random color, and to match searches against color names.
← `src/seo.json`: When you're ready to share your new site or add a custom domain, change SEO/meta settings in here.
## Next steps 🚀
Let's keep track of the submitted favorites using an array. First add this code near the top of `server.js`:
```js
const favorites = [];
```
In the `POST` route, inside the `if(color)` block, add this code to save the submitted value to the array, and write it to the console:
```js
favorites.push(color);
console.log(favorites);
```
Click __Tools__ > __Logs__ at the bottom of Glitch to see the log statement in action when you submit new colors through the form.
Clearly this is not a robust data storage approach and won't persist for long! Your Node apps can use a variety of databases, like [SQLite](https://glitch.com/~hello-sqlite) and [Airtable](https://glitch.com/~airtable-guestbook-starter).
![Glitch](https://cdn.glitch.com/a9975ea6-8949-4bab-addb-8a95021dc2da%2FLogo_Color.svg?v=1602781328576)
## You built this with Glitch!
+11
View File
@@ -188,3 +188,14 @@ label {
color: #000000;
font-weight: bold;
}
/* Instructions */
.instructions {
margin: 1rem auto 0;
}
.instructions p {
font-size: 1rem;
}
h2 {
color: #2800FF;
}
+26 -12
View File
@@ -1,11 +1,19 @@
/*
This is the main Node.js server script for your project
- The two endpoints this back-end provides are defined in fastify.get and fastify.post below
*/
const path = require("path");
// Require the fastify framework and instantiate it
const fastify = require("fastify")({
// set this to true for detailed logging:
// Set this to true for detailed logging:
logger: false
});
// ADD FAVORITES ARRAY VARIABLE FROM README HERE
// Setup our static files
fastify.register(require("fastify-static"), {
root: path.join(__dirname, "public"),
@@ -22,58 +30,64 @@ fastify.register(require("point-of-view"), {
}
});
// load and parse SEO data
// Load and parse SEO data
const seo = require("./src/seo.json");
if (seo.url === "glitch-default") {
seo.url = `https://${process.env.PROJECT_DOMAIN}.glitch.me`;
}
// Our home page route, this pulls from src/pages/index.hbs
// Our home page route, this returns src/pages/index.hbs with data built into it
fastify.get("/", function(request, reply) {
// params is an object we'll pass to our handlebars template
let params = { seo: seo };
// check and see if someone asked for a random color
// If someone clicked the option for a random color it'll be passed in the querystring
if (request.query.randomize) {
// we need to load our color data file, pick one at random, and add it to the params
// We need to load our color data file, pick one at random, and add it to the params
const colors = require("./src/colors.json");
const allColors = Object.keys(colors);
let currentColor = allColors[(allColors.length * Math.random()) << 0];
// Add the color properties to the params object
params = {
color: colors[currentColor],
colorError: null,
seo: seo
};
}
// The Handlebars code will be able to access the parameter values and build them into the page
reply.view("/src/pages/index.hbs", params);
});
// A POST route to handle and react to form submissions
fastify.post("/", function(request, reply) {
// Build the params object to pass to the template
let params = { seo: seo };
// the request.body.color is posted with a form submission
// If the user submitted a color through the form it'll be passed here in the request body
let color = request.body.color;
// if it's not empty, let's try to find the color
// If it's not empty, let's try to find the color
if (color) {
// load our color data file
// ADD CODE FROM README HERE TO SAVE SUBMITTED FAVORITES
// Load our color data file
const colors = require("./src/colors.json");
// take our form submission, remove whitespace, and convert to lowercase
// Take our form submission, remove whitespace, and convert to lowercase
color = color.toLowerCase().replace(/\s/g, "");
// now we see if that color is a key in our colors object
// Now we see if that color is a key in our colors object
if (colors[color]) {
// found one!
// Found one!
params = {
color: colors[color],
colorError: null,
seo: seo
};
} else {
// try again.
// No luck! Return the user value as the error property
params = {
colorError: request.body.color,
seo: seo
};
}
}
// The Handlebars template will use the parameter values to update the page with the chosen color
reply.view("/src/pages/index.hbs", params);
});
+32 -11
View File
@@ -1,13 +1,20 @@
<!DOCTYPE html>
<html lang="en">
<head>
<!--
This is the main Handlebars template for the site
- When the user visits the homepage or submits a color the app calls the endpoints in server.js
- The server script passes data in here and the Handlebars code builds it into the HTML page
-->
<meta charset="utf-8" />
<link rel="icon" href="https://glitch.com/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>{{seo.title}}</title>
<!-- meta tags for SEO and social sharing -->
<!-- Meta tags for SEO and social sharing -->
<link rel="canonical" href="{{seo.url}}">
<meta name="description" content="{{seo.description}}">
<meta property="og:title" content="{{seo.title}}">
@@ -17,11 +24,12 @@
<meta property="og:image" content="{{seo.image}}">
<meta name="twitter:card" content="summary">
<!-- import the webpage's stylesheet -->
<!-- Import the webpage's stylesheet -->
<link rel="stylesheet" href="/style.css" />
<!-- this is a handlebars IF statement, checking for a custom "color" parameter set in server.js -->
<!-- This is a handlebars IF statement, checking for a custom "color" parameter set in server.js -->
{{#if color}}
<!-- If there is a color value, update the style for the page title -->
<style>
.title {
color: {{color}};
@@ -32,10 +40,10 @@
<body>
<div class="wrapper">
<div class="content" role="main">
<!-- this is the start of content for our page -->
<!-- This is the start of content for our page -->
<h1 class="title">Hello Node!</h1>
<!-- add text indicating that we've changed color OR had an error -->
<!-- Add text indicating that we've changed color OR had an error -->
{{#if color}}
<p class="color-info">
Now available in <b>{{color}}</b>!
@@ -43,13 +51,14 @@
{{/if}}
{{#if colorError}}
<p class="color-info">
<!-- The server script passes colorError if the user submission can't be matched -->
Hmm. Couldn't find <b>"{{colorError}}"</b>.
<a href="?randomize=go">Try a random color?</a>
</p>
{{/if}}
<div class="color-form">
<!-- our default paragraph/message -->
<!-- Our default paragraph/message -->
{{#unless colorError}}
{{#unless color}}
<!-- There are fancier ways to do this, but nesting two "#unless" statements sets up a "if these are both missing..." condition -->
@@ -59,10 +68,10 @@
{{/unless}}
{{/unless}}
<!-- the "what's your favorite color?" form sends a POST to the server, check server.js to see how it works -->
<!-- The "What's your favorite color?" form sends a POST request to the server, check server.js to see how it works -->
<form class="color-search" method="post">
<label for="color">
<!-- we use the handlebars "#if" statement so the form can adapt to its situation -->
<!-- We use the handlebars "#if" statement so the form can adapt to its situation -->
{{#if color}}
Try another color?<br>
{{else}}
@@ -70,20 +79,32 @@
{{/if}}
<input id="color" name="color" required="required" type="text">
</label>
<!-- If the user submits a value through the form it'll be passed to the server in the request body -->
<button type="submit">Submit</button>
</form>
<!-- this randomize link communicates with the server (server.js) using a querystring and GET request instead of a form POST -->
<!-- This randomize link communicates with the server (server.js) using a querystring and GET request instead of a form POST -->
Can't decide? <a href="?randomize=go">Use a random color!</a>
</div>
<div class="illo-container">
<img src="https://cdn.glitch.com/c62efef6-1e75-45cf-b248-afeccdda9477%2Fillustration.svg?v=1618196069568" class="illustration" alt="Node logo" />
</div>
<!-- Instructions on using this project -->
<div class="instructions">
<h2>
Using this project
</h2>
<p>
This is the Glitch <strong>Hello Node</strong> project. You can
use it to build your own app. Check out README.md in the editor for
more info and next steps you can take!
</p>
</div>
</div>
</div>
<!-- the footer holds our remix button — you can use it for structure or cut it out ✂ -->
<!-- The footer holds our remix button — you can use it for structure or cut it out ✂ -->
<footer class="footer">
<div class="links"></div>
<a