【问题标题】:How to append client-side scripts to page in Node如何将客户端脚本附加到 Node 中的页面
【发布时间】:2022-01-29 00:18:43
【问题描述】:

我正在启动项目 ts、node、express。 有没有办法将打字稿文件添加到在客户端运行的 html/ejs 中(所以我可以访问文档等,就像在常规 js 脚本中一样)?

所以应该是这样的:

  • 带有 express 的节点服务器,可返回 html 页面并处理用户登录/注册请求。
  • 在客户端脚本中的用户活动句柄上添加、删除、更改 html 中的元素。

我会很感激指出我在整个节点中误解的内容,如果我这样做了,请表达概念。

【问题讨论】:

    标签: javascript node.js typescript express


    【解决方案1】:

    详细说明请参考此链接: Serving html from express

    您基本上可以通过 express 提供 html 页面。 在根请求处理程序上,您可以服务器 index.html

    app.get('/', (req, res)=>{res.render('index.html');}
    

    现在在 index.html 页面中有一个指向 /index 路由示例的链接:

    <a href="/login">
    

    现在,在服务器代码上有一个路由处理程序

    app.get('/login', (req, res)=>{res.render('login.html');}
    

    login.html 现在可以有一个带有操作的表单

    <form action="/signin" method="post">
    <input type="text" name="username" placeholder="Username" required>
    <input type="password" name="password" placeholder="Password" required>
    <input type="submit" value="login">
    </form>
    

    现在,在服务器代码上有一个路由处理程序

    app.post('signin', (req, res)=>{//handle logic here});
    

    【讨论】:

    • 好的,我已经理解了发布请求。但是,如果我们说我有一个视图 - index.html 和一个 div。我有一个包含一些事件监听器的 script.ts 文件。如何将此脚本附加到我的 html 中?
    • 我不确定 TS,因为它需要先编译,因为您不能直接在浏览器上运行 TS,但是 js 文件您可以像通常使用脚本标签一样简单地添加 js 文件.将 js 文件保存在 express_project_path/public/js/demo.js 中
    • 要使用 ts 文件,我想你必须使用 tsc 并在 package.json 中写一个命令(比如有“start”:“node index.js”)来将 ts 编译成 js n 然后启动服务器。虽然我不确定这个设置很抱歉;(
    • 哦,谢谢。所以我只需添加文件夹“public”来表达静态,然后我可以引用这个文件夹中的文件吗?像
    猜你喜欢
    • 2011-05-24
    • 1970-01-01
    • 1970-01-01
    • 2017-09-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-11
    相关资源
    最近更新 更多