如何在 Express 和 Express 中使用 Vanilla JS 文件节点js

发布于 2025-01-14 12:15:21 字数 2997 浏览 3 评论 0原文

Index.html 文件时,普通的 javascript 文件不起作用

你好,我仍在学习 Express 和 Node js 我想创建一个单页应用程序,其中包含我已经完成的路由,尽管当我使用 Express Express 代码

import workout from "./views/workout.js";
import nutrition from "./views/nutrition.js";
import settings from "./views/settings.js";
import registration from "./views/registration.js";

const navigateTo = url => {
    history.pushState(null , null , url);
    router();
};

const router = async () =>{
    const routes = [
        {path: "/", view: Dashboard},
        {path: "/workout", view: workout},
        {path: "/nutrition", view: nutrition},
        {path: "/settings", view: settings},
        {path: "/registration", view: registration}
    ];

    // Test each route
    const potentialMatches = routes.map(route =>{
        return{
            route: route,
            isMatch: location.pathname === route.path
        }
    });

    let match = potentialMatches.find(potentialMatch => potentialMatch.isMatch);

    if(!match){
        match ={
            route: routes[0],
            isMatch: true
        }
    }
    const view = new match.route.view()

    document.querySelector("#app").innerHTML = await view.getHtml();
    

    console.log(match.route.view());
};
window.addEventListener("popstate", router);
document.addEventListener("DOMContentLoaded", () =>{
    
    document.body.addEventListener('click', e=>{
        if (e.target.matches("[data-link]")) {
            e.preventDefault();
            navigateTo(e.target.href);
        }
    });

    router();
});


服务器代码

const express = require("express");
const path = require("path");

const app = express();

app.use('/static' ,express.static(path.resolve(__dirname,"static")));



app.get("/*" , (req,res)=> {
    res.sendFile(path.resolve(__dirname,"index.html"));
    
});


app.get("/*" , (req,res)=> {
    
});


app.listen(process.env.PORT || 8080, () => console.log('Server Running....'));

调用 js 文件

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <!-- Boxicons -->
    <link href='https://unpkg.com/[email protected]/css/boxicons.min.css' rel='stylesheet'>
    
        <link href="http://fonts.googleapis.com/css?family=Cookie" rel="stylesheet" type="text/css">
        <!-- My CSS -->
    <link rel="stylesheet" href="/static/css/index.css">
    <script type="module" src="static/index.js"></script>
    <script  async src="static/nav.js"></script>

解释

我想要运行它的常规 javascript 文件不起作用,我将其移至静态目录,但我只是遇到此问题 Uncaught

TypeError:锻炼_容器为空 http://localhost:8080/static/nav.js:19

所有按钮都不起作用,只有常规 console.log 起作用,但其他页面功能和事件监听器不起作用,请帮忙,

谢谢

Hello I am Still learing Express and Node js I want to create a single page application with routes which i have done altho the vanilla javascript file is not working when i use express

Express Code

import workout from "./views/workout.js";
import nutrition from "./views/nutrition.js";
import settings from "./views/settings.js";
import registration from "./views/registration.js";

const navigateTo = url => {
    history.pushState(null , null , url);
    router();
};

const router = async () =>{
    const routes = [
        {path: "/", view: Dashboard},
        {path: "/workout", view: workout},
        {path: "/nutrition", view: nutrition},
        {path: "/settings", view: settings},
        {path: "/registration", view: registration}
    ];

    // Test each route
    const potentialMatches = routes.map(route =>{
        return{
            route: route,
            isMatch: location.pathname === route.path
        }
    });

    let match = potentialMatches.find(potentialMatch => potentialMatch.isMatch);

    if(!match){
        match ={
            route: routes[0],
            isMatch: true
        }
    }
    const view = new match.route.view()

    document.querySelector("#app").innerHTML = await view.getHtml();
    

    console.log(match.route.view());
};
window.addEventListener("popstate", router);
document.addEventListener("DOMContentLoaded", () =>{
    
    document.body.addEventListener('click', e=>{
        if (e.target.matches("[data-link]")) {
            e.preventDefault();
            navigateTo(e.target.href);
        }
    });

    router();
});


Server Code

const express = require("express");
const path = require("path");

const app = express();

app.use('/static' ,express.static(path.resolve(__dirname,"static")));



app.get("/*" , (req,res)=> {
    res.sendFile(path.resolve(__dirname,"index.html"));
    
});


app.get("/*" , (req,res)=> {
    
});


app.listen(process.env.PORT || 8080, () => console.log('Server Running....'));

Index.html file Calling js file

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <!-- Boxicons -->
    <link href='https://unpkg.com/[email protected]/css/boxicons.min.css' rel='stylesheet'>
    
        <link href="http://fonts.googleapis.com/css?family=Cookie" rel="stylesheet" type="text/css">
        <!-- My CSS -->
    <link rel="stylesheet" href="/static/css/index.css">
    <script type="module" src="static/index.js"></script>
    <script  async src="static/nav.js"></script>

Explanation

I want the regular javascript file to run it is not working i moved it to the static directory but i just get this issue Uncaught

TypeError: workout_container is null
http://localhost:8080/static/nav.js:19

None of the buttons are working only a regular console.log works but the other pages functions and event listners arent working please help

Thank you

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文