【问题标题】:Loading local jquery.js file in node js在节点 js 中加载本地 jquery.js 文件
【发布时间】:2015-02-22 17:39:51
【问题描述】:

我想在我的节点 js 聊天应用程序中加载本地 jquery 文件。我已经搜索了很多,但我找不到合适的解决方案。

<!doctype html>
<html>
  <head>
    <title>Socketio</title>
  </head>
  <body>
      <!--This wont work -->
      <script src="/socket.io/jquery.min.js"></script> 
        <!--This will work -->
      <script src="/socket.io/socket.io.js"></script>

  </body>
</html>

我只是将 jquery.js 文件复制到 socket.io 文件夹。socket.io.js 文件正确加载但 jquery 文件没有。请帮助我 这是我的 index.js 文件

var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);


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

server.listen(3000, function(){
  console.log('listening on *:3000');
});

【问题讨论】:

  • 服务器端需要 jQuery 做什么?也许你想在 index.html 上加载它?
  • 是的,我想在客户端加载文件
  • 而不是像通常在 index.html 上那样放置它
  • 但它没有工作。我会得到错误 cannot GET jquery file

标签: javascript jquery node.js socket.io


【解决方案1】:

您可能希望允许 Express 框架呈现 HTML 并传入静态 jQuery 文件。我就是这样做的。

This page 解释了如何重组应用程序以通过节点路由而不是 HTML 代码来提供 jquery 文件。

【讨论】:

  • 有点复杂。
【解决方案2】:

一种解决方法是使用在线源文件链接。 尝试使用以下加载 jquery,

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

这对我来说很好用。

【讨论】:

    【解决方案3】:

    终于找到了答案。我只是通过http://localhost/assets/jquery.min.js这种方式从localhost加载jquery文件。

    【讨论】:

      【解决方案4】:
      app.get('/jquery', function(res, req){
         res.sendFile(__dirname + '/jquery.js');
      });
      

      【讨论】:

      • 你能解释一下吗?
      • 抱歉解释晚了。这意味着如果您向 baseurl/jquery 发送请求,响应将是 jquery.js
      【解决方案5】:
      app.use('/assets', express.static('assets'))
      

      将您的 jquery.min.js 文件放在相对“/assets/jquery.min.js”路径中,然后以http://localhost/assets/jquery.min.js 访问

      "localhost" 也可以是您的 IP 地址。

      就个人而言,我需要这个,因为我需要一个完全独立的演示来独立于可用的互联网连接运行。墨菲定律在会议时间到来时仍然有效。

      【讨论】:

        【解决方案6】:

        这对我有用。 (在 app.js 中)

        const express = require('express');//path to express module
        const path = require('path');
        const app = express();
        app.use(express.static(path.join(__dirname, 'public')));
        

        我的文件结构如下所示:

          server.js
          app.js
        > public
            index.html
          > assets
            > js
                jquery.min
        

        然后像往常一样从 index.html 导入 jquery:

        <script src="assets/js/jquery-3.3.1.min.js"></script>
        

        【讨论】:

          猜你喜欢
          • 2016-08-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-06-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-06-23
          相关资源
          最近更新 更多