简体   繁体   中英

How do I connect my html code to controllers and routes in javascript?

HTML code that needs to be the front end.

It should take the input from the user and the information that needs to be converted to JSON format and posted on a file which is hosted on a server.

I also need to be able to edit the json file through my HTML page itself.

    <!DOCTYPE html>
    <html>

    <head>
    <title>
        News
    </title>
    <link rel="stylesheet" href="style.css">
    </head>

    <body>

    <h1><center>News Form</center></h1>
    <hr>
            <div class="news-form">
                <form onsubmit="event.preventDefault();onFormSubmit();" autocomplete="off">
                    <div>
                        <label for="trending">Trending?</label><br>

                        <select name="trending" id="trending">
                        <option value="yes">yes</option>
                        <option value="no">no</option>
                        
                        </select> <br>  
                       
                    </div>
                    <div><br>
                        <label>Image Link</label><label class="validation-error hide"   id="ValidationError">This field is required!</label>
                        <input type="text" name="image" id="image">
                    </div>
                    <div>
                        <label>Heading</label>
                        <input type="text" name="heading" id="heading">
                    </div>
                    <div>
                        <label>Content</label>
                        <input type="text" name="content" id="content">
                    </div> <br>
                    <div>
                        <label for="genres">Choose a category:</label>
                         <br>   
                        <select name="genres" id="genres">
                        <option value="finance">finance</option>
                        <option value="politics">politics</option>
                        <option value="sports">sports</option>
                        <option value="business">business</option>
                        </select>
                        
                    </div>
                    <div  class="form-action-buttons">
                        <input type="submit" value="Submit">
                    </div>
                </form>
        </div>
        <br/>
        <div class = "news-table">
                <table class="list" id="newsList">
                    <thead>
                        <tr>
                            <th>Trending</th>
                            <th>Image Link</th>
                            <th>Heading</th>
                            <th>Content</th>
                            <th>Genres</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>

                    </tbody>
                </table>
        </div>
       <script src="script.js"></script>
       </body>
       </html>

The Controller which should take the data from the HTML page and send to server:


    import { v4 as uuidv4 } from 'uuid';
    let users =[]

    export const createNews =(req,res) =>{
                                        const newuser= req.content;
                                                                                   
                                        users.push({...newuser, id: uuidv4()});
                                        console.log('post route reached');
                                                                                   
                                        res.send(`User with the heading ${newuser.heading} added to  the database!`);}


    export const getNewsonid =(req,res)=>{
                                        const {id} = req.params;
                                        const founduser= users.find((newuser) => newuser.id = id );
                                        console.log(req.params);
                                          
                                        res.send(founduser);
                                        res.send('THE GET ID ROUTE');                     
    }

    export const deleteNews =(req,res)=>{
                                        const {id} = req.params ;
                                        users = users.filter((newuser)=>newuser.id != id);
                                        res.send(`User with id ${id} deleted from the database`);
        
    }

    export const updateNews =(req,res)=>{
                                        const {id} = req.params ;
                                        const newuser= users.find((newuser)=>newuser.id = id);
                                        const {heading,trending,category,content} = req.body;
                                        if (heading) newuser.heading =heading;
                                        if (trending) newuser.trending =trending;
                                        if (category) newuser.category=category;
                                        if (content) newuser.content=content;
                                        res.send(`User with ${id}, has been updated!`)     
     }

     export const getAllNews =(req,res)=>{
                                        res.send(users);
                                        console.log('printed');                                 
     }

The Route javascript file:

    import express from 'express';
    import {createNews} from "../controllers/users.js";
    import {getNewsonid} from "../controllers/users.js";
    import {deleteNews} from "../controllers/users.js";
    import {updateNews,getAllNews} from "../controllers/users.js";

     const router = express.Router();

    router.get('/',getAllNews);                                  
    router.post('/',createNews);
    router.get('/:id',getNewsonid);
    router.delete('/:id',deleteNews)
    router.patch('/:id',updateNews)

    export default router;

The server code:

     import express from 'express';
     import bodyParser from 'body-Parser';
     import usersRoutes from './routes/users.js';
     const app = express();
     const port = 5000;
     import http from 'http';

     import path from 'path';
     import { fileURLToPath } from 'url';
     const __filename = fileURLToPath(import.meta.url);
     const __dirname = path.dirname(__filename);

    app.use(bodyParser.json());// we will be using json to convey and accept our requests

     app.get('/',function(req,res) {
      res.sendFile('/index.html', { root: __dirname });
     });

    app.use('/users',usersRoutes);

    app.listen(port, () =>{
                        console.log(`Server Running on port : http://localhost:${port}`)                  
    })

    app.get('/',(req,res)=>{
             console.log('Print on terminal');
             res.send(`Server Running on port : http://localhost:${port}`)                             
    });

I also need to connect this scriptfile so that the information that is being sent on the JSON can be viewed and edited from the HTML file itself.

    var selectedRow = null

    function onFormSubmit() {
    if (validate()) {
        var formData = readFormData();
        if (selectedRow == null)
            insertNewRecord(formData);
        else
            updateRecord(formData);
        resetForm();
    }
    }

    function readFormData() {
    var formData = {};
    formData["trending"] = document.getElementById("trending").value;
    formData["image"] = document.getElementById("image").value;
    formData["heading"] = document.getElementById("heading").value;
    formData["content"] = document.getElementById("content").value;
    formData["genres"] = document.getElementById("genres").value;
    return formData;
    }

    function insertNewRecord(data) {
    var table = document.getElementById("newsList").getElementsByTagName('tbody')[0];
    var newRow = table.insertRow(table.length);
    cell0 = newRow.insertCell(0);
    cell0.innerHTML = data.trending;
    cell1 = newRow.insertCell(1);
    cell1.innerHTML = data.image;
    cell2 = newRow.insertCell(2);
    cell2.innerHTML = data.heading;
    cell3 = newRow.insertCell(3);
    cell3.innerHTML = data.content;
    cell4 = newRow.insertCell(4);
    cell4.innerHTML = data.genres;
    cell4 = newRow.insertCell(5);
    cell4.innerHTML = `<a onClick="onEdit(this)">Edit</a>
                       <a onClick="onDelete(this)">Delete</a>`;
    }

    function resetForm() {
    document.getElementById("trending").value = "";
    document.getElementById("image").value = "";
    document.getElementById("heading").value = "";
    document.getElementById("content").value = "";
    document.getElementById("genres").value = "";
    selectedRow = null;
    }

    function onEdit(td) {
    selectedRow = td.parentElement.parentElement;
    document.getElementById("trending").value = selectedRow.cells[0].innerHTML;
    document.getElementById("image").value = selectedRow.cells[1].innerHTML;
    document.getElementById("heading").value = selectedRow.cells[2].innerHTML;
    document.getElementById("content").value = selectedRow.cells[3].innerHTML;
    document.getElementById("genres").value = selectedRow.cells[4].innerHTML; 
    }
     function updateRecord(formData) {
    selectedRow.cells[0].innerHTML = formData.trending;
    selectedRow.cells[1].innerHTML = formData.image;
    selectedRow.cells[2].innerHTML = formData.heading;
    selectedRow.cells[3].innerHTML = formData.content;
    selectedRow.cells[4].innerHTML = formData.genres;
    }

    function onDelete(td) {
    if (confirm('Are you sure to delete this record ?')) {
        row = td.parentElement.parentElement;
        document.getElementById("newsList").deleteRow(row.rowIndex);
        resetForm();
    }
    }
    function validate() {
    isValid = true;
    if (document.getElementById("image").value == "") {
        isValid = false;
        document.getElementById("ValidationError").classList.remove("hide");
    } else {
        isValid = true;
        if (!document.getElementById("ValidationError").classList.contains("hide"))
            document.getElementById("ValidationError").classList.add("hide");
    }
    return isValid;
    }

I have been trying for the last 5 day to no avail. Please provide any feedback on how to make the connections and make this work.

I also keep getting MIME error. Then I added the javascript file directly to the HTML page, but then it says UnCaught Reference: onFormSubmit not defined.

I also get error: Promised response from onMessage listener went out of scope

AFAIN, the connection is the html-file, in head or body as last entry.

Like this incomplete example index.html with scripts:

<!DOCTYPE html>
<html>

<!-- START. Your html code -->

<head>
    <!-- Favicon-->
    <link rel="icon" type="image/x-icon" href="/static/assets/favicon.ico" />
    <!-- Font Awesome icons (free version)-->
    <script src="https://use.fontawesome.com/releases/v5.15.3/js/all.js" crossorigin="anonymous"></script>

</head>
<body>

<!-- END. Your html code -->

    <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
    <script src="/static/js/scripts.js"></script>
    <script src="/static/js/jqBootstrapValidation.js"></script>
    <script src="/static/js/contact_me.js" type="text/javascript"></script>
<!--  -->

</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM