【问题标题】:where to keep my frontend js file while using node? [closed]使用节点时在哪里保存我的前端 js 文件? [关闭]
【发布时间】:2020-10-06 13:25:19
【问题描述】:

我使用 html css 和 js 制作了一个待办事项列表。现在我想要一个后端将我的项目存储在数据库中。在这个阶段,我将我与 html 和 css 一起创建的 js 文件存储在哪里。我已将它放在公用文件夹和公用文件夹之外,但它在我运行服务器时无法正常工作。我的待办事项列表没有执行添加、删除或编辑的功能。这三个函数是我在js文件中创建的。

【问题讨论】:

  • 可能是./src/js/
  • 你的服务器代码在 index.js 中吗?如果是这样,那就是我们需要查看的代码。不是 app.js
  • 是的,我的服务器代码在 index.js 中
  • 请帮忙.....
  • 我们需要查看您的服务器代码。您需要启用公用文件夹来提供文件,而不是使用节点解释它们。您可以使用 express 框架在几行内完成此操作

标签: javascript html css node.js express


【解决方案1】:

在你的根目录中运行npm install express

在项目根目录的index.js 文件中:

// Use the express framework to speed things up
const express = require('express');

// Create an app instance which you will use to start your server
const app = express();
// Use a constant for which Port you want to start your server on
const port = 3000;

// HERE IS THE STUFF TO MAKE THE PUBLIC DIRECTORY SERVE STATIC FILES
// app.use(urlPath, middleware) - execute middleware when urlPath is requested
// express.static(filepath) - Is a pre-packaged middleware that will serve
// the contents of the filepath as static files
// '/public' says visit: 'http://localhost:3000/public' to view the contents
// of the directory
app.use('/public', express.static('public'));

// if running on your localhost the you will see the 
// below message if you visit http://localhost:3000
// after starting your server 
app.get('/', (req, res) => {
  res.send('Hello World, my server is up and running!');
});

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`);
});

现在您的服务器已设置为从您的 public 目录中服务器静态文件。

通过在根目录中运行node index.js 来启动服务器。打开浏览器并访问http://localhost:3000,您应该会看到消息Hello World, my server is up and running!

导航到http://localhost:3000/public,您应该会看到公共目录的内容。

导航到http://localhost:3000/public/<fileName>,您应该会看到特定文件或图像的内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-19
    • 1970-01-01
    • 2017-01-07
    • 1970-01-01
    • 2013-08-25
    • 2016-08-10
    • 2020-06-27
    • 2013-11-08
    相关资源
    最近更新 更多