Demonstrate the process of routing JSON information to various endpoints

As a beginner with express, I've found the responses on StackOverflow to be quite perplexing. Currently, I am working with JSON data that I retrieve using app.get(). My goal is to manipulate this data and send it to my index.html file. While I understand that I can easily fetch the data in my index file from the get endpoint, I also need to utilize both the app.post() and app.put() functions.

Answer №1

I'm struggling to comprehend the query you've presented.

Below is a snippet of code that showcases how axios and JavaScript can be utilized together to retrieve data from the backend and allow for modifications on the frontend. Feel free to substitute axios with fetch for similar functionality.

app.js

const express = require("express");
const bodyParser = require("body-parser");
const port = 8000;

const app = express();

/* Simulating data, although utilizing a storage solution like MySQL would be ideal */
let data = {
    name: "Elon Musk",
    age: "48",
    height: "1.88m"
};

app.use(express.static("public"));
/* body-parser is necessary for the server to parse incoming data */
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

/* endpoint to fetch data */
app.get("/api/mydata", function(req, res) {
    return res.json(data);
});

/* endpoint where the client posts updated data */
app.post("/api/newdata", function(req, res) {
    data.name = req.body.name;
    data.age = req.body.age;
    return res.json("OK!");
});

app.listen(port, function() {
    console.log("Listening on port 8000");
});

public/index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>

    <input type="text" id="name" placeholder="Name..." value="">
    <input type="text" id="age" placeholder="Age..." value="">

    <button type="button" id="setValues">Change values!</button>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.js"></script>
    <script>
        window.addEventListener("load", function() {
            axios.get("/api/mydata").then(function(res) {
                document.getElementById("name").value = res.data.name;
                document.getElementById("age").value = res.data.age;
            })
        });

        document.getElementById("setValues").addEventListener("click", function() {
            axios.post("/api/newdata", { 
                name: document.getElementById("name").value,
                age: document.getElementById("age").value
            }).then(function(res) {
                console.log("Data Sent!");
            })
        })
    </script>
</body>
</html>

If there are any uncertainties, please don't hesitate to reach out!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A guide on validating dates in Angular Ionic5 with the help of TypeScript

I have tried multiple solutions, but none seem to work when validating the current date with the date entered by the user. The date is passed from the user into the function parameters, but how do I perform validation? How can I validate the date? isToday( ...

Keep retrieving information until the outcome becomes an empty array

I'm currently implementing the Selly API in my project and I've encountered an issue with fetching all products as the Selly API paginates the results. To overcome this, my approach is to fetch all products, store them in an array, and then outp ...

Enhance your code with TinyMCE scripting

Currently, I am exploring methods to incorporate an external script into tinymce. The specific script in question is p7EHCscript which is designed to ensure two divs have equal heights based on the larger div's height. I aim to integrate the p7EHC sc ...

Sharing data between functions in jQuery AJAX promises

Struggling to define a variable in one promise method and use it in another? Here's the scenario: Take a look at this code snippet: $.getJSON('some/file/') .done(function(response) { var bar = response; }) .always(function() { // N ...

What is the best method for animating a display table to none or reducing its height to

My goal is to animate a header whenever the class collapseTest is applied. After some trial and error, I have come up with the following solution: http://jsfiddle.net/robertrozas/atuyLtL0/1/. A big shoutout to @Hackerman for helping me get it to work. The ...

Filtering Images by Alt Attribute: A Comprehensive Guide

I'm working on an image gallery project that includes a search box feature. My goal is to dynamically hide images that do not have an alt attribute matching the user's search query. Despite several attempts, I keep encountering issues where all e ...

How to clear a 24-hour-old template from the Angular 1 cache?

I have implemented the following rule to clear template cache in my AngularJS application: myApp.run(function ($rootScope, $templateCache) { $rootScope.$on('$viewContentLoaded', function() { $templateCache.removeAll(); }); }); Howe ...

Delete a specific row from a table in one parent container based on the content of another parent

Before accusing this of being a duplicate, please read carefully. I have a unique table structure that appears as follows: <td> <table class="schedule_day_table"> <tr> &l ...

Creating a flexible grid layout using Flexbox and JavaScript media queries to dynamically adjust container size

I enjoy working on Etch-a-Sketch projects from The Odin Project, but I am looking to take it a step further than just the assignment. I want to challenge myself by achieving this solely with Flexbox and JavaScript, without involving CSS Grid. When I se ...

Show the form when the button is clicked

I want to create an application that allows users to click on a button in the top right corner (check image) to hide one div (topics) and show another div (a form for adding a new topic). Here is what it looks like: https://i.stack.imgur.com/YeRTw.png ...

Ways to eliminate the vertical scroll feature in a kendo chart

I am encountering an issue while loading a kendo chart inside grid-stack.js where I am unable to resize the height properly. Whenever I decrease the height, a vertical scroll appears which should not happen. I have tried setting the height to auto and refr ...

Unchecking a box becomes impossible in Rails and Ajax due to boolean constraints

Even though I've come across several similar questions, I'm still struggling to make mine work correctly. Here's what my code looks like... #app/views/tasks/index.html.erb <%- @tasks.each do |task| %> <div class="task-wrapper"> ...

Encountering the issue "Error: listen EACCES" when trying to launch an application using pm2 on port 80?

When attempting to start my nodejs app on port 80 using pm2 on Ubuntu, we encountered an error message **Error: listen EACCES**. Our pm2 version is 0.12.7 and the command we used was: sudo pm2 start app.js -- dev The result of running whereis node showed ...

What is the reason behind the effectiveness of this prime number verifier?

Take a look at this code snippet that effectively checks whether a number is prime: var num = parseInt(prompt("Enter a number:")); var result = "Prime"; for (var i = 2; i < num; i++) { if (num % i === 0) { result = "Not Prime"; break; } } ...

Designated location for downloading specified by the user

I've been searching for a while now and I can't seem to find a satisfactory answer. Essentially, I have a website where users can input values and download a specific file based on those values. Everything is functional, but I want to give the u ...

In JavaScript, what do we call the paradigm where a variable equals a variable equals a function? Let's take

Feeling a bit overloaded at the moment, so forgive me if this question seems too simple. I managed to accidentally write some code in Jest for testing a Vue application that actually works: const updateMethod = wrapper.vm.updateMethod = jest.fn() expect(u ...

Broaden material-ui component functionality with forwardRef and typescript

To enhance a material-ui component with typescript, I have the javascript code provided in this link. import Button from "@material-ui/core/Button"; const RegularButton = React.forwardRef((props, ref) => { return ( <B ...

Tips for displaying a const variable's data type within HTML syntax

Here is my code snippet: {% load static %} {% block extrascript %} <script src="{% static 'js/batch/batch_detail.js' %}"></script> <script src="{% static 'js/audit_log/audit_log.js' %}"></script> < ...

There seems to be an issue with using JavaScript in an Asp.net environment

Implementing a function using jQuery to slide and fade a div element with jQuery UI Effects Slide 1.8.16. The code snippet includes the necessary scripts and stylesheets: <script src="js/Newfolder/jquery-ui-1.8.16.custom.min.js" type="text/javascript" ...

Firefox failing to trigger key events within iframe

For fun, I created my own little JSFiddle website where I built a Snake implementation that works great in Chrome. However, when I try to use it in Firefox, I can't control the player with the arrow keys or WASD. You can check it out here: I read on ...