Html css and mysql

so basically im doing a project where im making a single page web application with a mysql server and node.js , im not very good at coding and barely know what im doing,
so i implemented the following code ,
Here’s my html file :

<!DOCTYPE html>
<html>
  <head>
    <title>My Landing Page</title>
    <style>
      #recipe-container {
        background-color: #f7f7f7;
        padding: 20px;
      }
    </style>
    <!-- Add jQuery library and app.js file -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="app.js"></script>
  </head>
  <body>
    <h1>Welcome to my landing page!</h1>
    <p>This is some sample content.</p>
    
    <!-- Add a form to submit a new recipe -->
    <form id="add-recipe-form">
      <label for="title">Title:</label>
      <input type="text" id="title" name="title" required><br><br>
      <label for="description">Description:</label>
      <textarea id="description" name="description" required></textarea><br><br>
      <label for="image-url">Image URL:</label>
      <input type="text" id="image-url" name="image-url"><br><br>
      <input type="submit" value="Add Recipe">
    </form>
    
    <!-- Display the list of recipes -->
    <div id="recipe-container">
      <ul id="recipe-list"></ul>
    </div>
    
    <script>
      // Get the list of recipes from the server and display it
      fetch('/recipes')
        .then(response => response.json())
        .then(data => {
          let recipesList = document.querySelector('#recipe-list');
          let recipesHTML = '';
          data.forEach(recipe => {
            recipesHTML += `<li><h2>${recipe.title}</h2>`;
            recipesHTML += `<p>${recipe.description}</p>`;
            recipesHTML += `<img src="${recipe.image_url}"></li>`;
          });
          recipesList.innerHTML = recipesHTML;
        })
        .catch(error => console.error(error));
        
      // Add a submit event listener to the form to submit a new recipe
      $('#add-recipe-form').submit(function(event) {
        event.preventDefault();
        let title = $('#title').val();
        let description = $('#description').val();
        let imageUrl = $('#image-url').val();
        fetch('/recipes', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            title: title,
            description: description,
            image_url: imageUrl
          })
        })
        .then(response => response.json())
        .then(data => {
          $('#add-recipe-form')[0].reset();
          let recipesList = document.querySelector('#recipe-list');
          let recipeHTML = `<li><h2>${data.title}</h2>`;
          recipeHTML += `<p>${data.description}</p>`;
          recipeHTML += `<img src="${data.image_url}"></li>`;
          recipesList.insertAdjacentHTML('beforeend', recipeHTML);
        })
        .catch(error => console.error(error));
      });
    </script>
  </body>
</html>

here’s my js :

const mysql = require('mysql');
const express = require('express');
const app = express();
const bodyParser = require('body-parser');

// create a connection pool to your MySQL server
const pool = mysql.createPool({
  connectionLimit: 10,
  host: 'localhost',
  user: 'root',
  password: 'password',
  database: 'recipe_box',
});

// Serve the landing page
app.use(express.static('public'));

// Parse incoming request bodies in a middleware before your handlers
app.use(bodyParser.json());

// GET request to retrieve all recipes
app.get('/recipes', function(req, res) {
  // query the recipes table and send the result as a JSON response
  pool.query('SELECT * FROM recipes', function(err, rows) {
    if (err) throw err;
    res.json(rows);
  });
});

// POST request to add a new recipe
app.post('/recipes', function(req, res) {
  const title = req.body.title;
  const description = req.body.description;
  const image_url = req.body.image_url;

  // Insert the new recipe into the recipes table
  pool.query('INSERT INTO recipes (title, description, image_url) VALUES (?, ?, ?)', [title, description, image_url], function(err, result) {
    if (err) throw err;

    // Retrieve the newly added recipe and send it back as a JSON response
    pool.query('SELECT * FROM recipes WHERE id = ?', result.insertId, function(err, rows) {
      if (err) throw err;
      res.json(rows[0]);
    });
  });
});

// Start the server
app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

now i know im supposed to open localHost :3000/recipes" to see my output but all i see is this (Screenshot attached) even though i have some css elements in my html , why is that and how do i fix it ?

Going directly to the route is like testing the response, just like using Postman or something like it. The browser just shows the JSON returned by the endpoint.

You have fetch code in your JS that will fetch from that resource and use the JSON that is returned. That JS will run when the client (the browser) hits the / route (most likely) that the page with the JS is served from.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.