【问题标题】:node.js TypeError: path must be absolute or specify root to res.sendFile [failed to parse JSON]node.js TypeError: path must be absolute or specified root to res.sendFile [failed to parse JSON]
【发布时间】:2014-11-22 15:33:44
【问题描述】:

[添加] 所以我的下一个问题是,当我尝试添加新的依赖项时(npm install --save socket.io)。 JSON 文件也是有效的。我收到此错误: 解析json失败

npm ERR! Unexpected string
npm ERR! File: /Users/John/package.json
npm ERR! Failed to parse package.json data.
npm ERR! package.json must be actual JSON, not just JavaScript.
npm ERR! 
npm ERR! This is not a bug in npm.
npm ERR! Tell the package author to fix their package.json file. JSON.parse 

所以我一直在试图弄清楚为什么这个错误一直在返回。所有文件(HTML、JSON、JS)都在我桌面上的同一个文件夹中。我正在使用 node.js 和 socket.io

这是我的 JS 文件:

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

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

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

这是返回的内容:

MacBook-Pro:~ John$ node /Users/John/Desktop/Chatapp/index.js 
listening on : 3000
TypeError: path must be absolute or specify root to res.sendFile
    at ServerResponse.sendFile (/Users/John/node_modules/express/lib/response.js:389:11)
    at /Users/John/Desktop/Chatapp/index.js:5:7
    at Layer.handle [as handle_request] (/Users/John/node_modules/express/lib/router/layer.js:76:5)
    at next (/Users/John/node_modules/express/lib/router/route.js:100:13)
    at Route.dispatch (/Users/John/node_modules/express/lib/router/route.js:81:3)
    at Layer.handle [as handle_request] (/Users/John/node_modules/express/lib/router/layer.js:76:5)
    at /Users/John/node_modules/express/lib/router/index.js:234:24
    at Function.proto.process_params (/Users/John/node_modules/express/lib/router/index.js:312:12)
    at /Users/John/node_modules/express/lib/router/index.js:228:12
    at Function.match_layer (/Users/John/node_modules/express/lib/router/index.js:295:3)
TypeError: path must be absolute or specify root to res.sendFile
    at ServerResponse.sendFile (/Users/John/node_modules/express/lib/response.js:389:11)
    at /Users/John/Desktop/Chatapp/index.js:5:7
    at Layer.handle [as handle_request] (/Users/John/node_modules/express/lib/router/layer.js:76:5)
    at next (/Users/John/node_modules/express/lib/router/route.js:100:13)
    at Route.dispatch (/Users/John/node_modules/express/lib/router/route.js:81:3)
    at Layer.handle [as handle_request] (/Users/John/node_modules/express/lib/router/layer.js:76:5)
    at /Users/John/node_modules/express/lib/router/index.js:234:24
    at Function.proto.process_params (/Users/John/node_modules/express/lib/router/index.js:312:12)
    at /Users/John/node_modules/express/lib/router/index.js:228:12
    at Function.match_layer (/Users/John/node_modules/express/lib/router/index.js:295:3)

【问题讨论】:

    标签: javascript json node.js socket.io dependencies


    【解决方案1】:
    app.get('/api', (req, res, next) => {
        res.sendFile('./public/index.html', { root: __dirname });
    });
    

    错误很明显,您需要在 res.sendFile() 的配置对象中指定绝对(而不是相对)路径和/或设置 root

    【讨论】:

      【解决方案2】:

      app.js 中的这个配置对我来说很好用:

          //production mode
      if (process.env.NODE_ENV === "production") {
        app.use(express.static(path.join(__dirname, "client/build")));
        app.get("*", (req, res) => {
          res.sendFile(path.join((__dirname + "/client/build/index.html")));
      
        });
      }
      
      //build mode
      app.get("*", (req, res) => {
        res.sendFile(path.join(__dirname + "/client/public/index.html"));
      
      });
      

      【讨论】:

        【解决方案3】:

        我使用下面的代码并尝试显示 sitemap.xml 文件

        router.get('/sitemap.xml', function (req, res) {
            res.sendFile('sitemap.xml', { root: '.' });
        });
        

        【讨论】:

          【解决方案4】:

          我这样做了,现在我的应用程序运行正常,

          res.sendFile('your drive://your_subfolders//file.html');
          

          【讨论】:

          • 硬编码文件的位置是不好的做法。如果您将应用程序部署到不同的机器上,文件的路径很可能会有所不同
          【解决方案5】:

          它将重定向到 localhost:8080 调用上的 index.html。

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

          【讨论】:

            【解决方案6】:

            在带有图标相对路径的 Typescript 中:

            import path from 'path';
            
            route.get('/favicon.ico', (_req, res) => res.sendFile(path.join(__dirname, '../static/myicon.png')));
            

            【讨论】:

              【解决方案7】:

              尝试添加根路径。

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

              【讨论】:

                【解决方案8】:

                如果您正在处理根目录,那么您可以使用这种方法

                res.sendFile(__dirname + '/FOLDER_IN_ROOT_DIRECTORY/index.html');
                

                但是如果您使用的是文件夹内的路由,可以说/Routes/someRoute.js,那么您将需要执行类似的操作

                const path = require("path");
                ...
                route.get("/some_route", (req, res) => {
                   res.sendFile(path.resolve('FOLDER_IN_ROOT_DIRECTORY/index.html')
                });
                
                

                【讨论】:

                  【解决方案9】:

                  我通过使用路径变量来解决这个问题。示例代码如下所示。

                  var path = require("path");
                  
                  app.get('/', (req, res) => {
                      res.sendFile(path.join(__dirname + '/index.html'));
                  })
                  

                  【讨论】:

                    【解决方案10】:

                    您可以考虑在目录上使用双斜杠,例如

                    app.get('/',(req,res)=>{
                        res.sendFile('C:\\Users\\DOREEN\\Desktop\\Fitness Finder' + '/index.html')
                    })

                    【讨论】:

                      【解决方案11】:

                      在 .mjs 文件中,我们现在没有 __dirname

                      因此

                      res.sendFile('index.html', { root: '.' })
                      

                      【讨论】:

                      • 这对我来说是一个很好的解决方案,因为我的要求是在通过 __dirname 获取路径后返回。所以我给了 res.sendFile('index.html', { root: './public /views' });
                      • 对于把手中的 SITEMAP.XML,这是正确的解决方案。非常感谢
                      【解决方案12】:

                      这可以通过另一种方式解决:

                      app.get("/", function(req, res){
                      
                          res.send(`${process.env.PWD}/index.html`)
                      
                      });
                      

                      process.env.PWD 将在进程启动时添加工作目录。

                      【讨论】:

                        【解决方案13】:

                        错误非常简单。最可能的原因是您的 index.html 文件不在根目录中。

                        或者如果它在根目录中,则相对引用不起作用。

                        所以你需要告诉服务器你的文件的确切位置。 这可以通过在 NodeJs 中使用 dirname 方法来完成。 只需用这个替换您的代码:

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

                        确保在主页前添加斜杠“/”符号。否则你的路径会变成:rootDirectoryindex.html

                        而你希望它是:rootDirectory/index.html

                        【讨论】:

                          【解决方案14】:

                          如果您信任路径,则 path.resolve 是一个选项:

                          var path = require('path');
                          
                          // All other routes should redirect to the index.html
                            app.route('/*')
                              .get(function(req, res) {
                                res.sendFile(path.resolve(app.get('appPath') + '/index.html'));
                              });
                          

                          【讨论】:

                            【解决方案15】:

                            错误很明显,您需要指定一个绝对(而不是相对)路径和/或在res.sendFile() 的配置对象中设置root。例子:

                            // assuming index.html is in the same directory as this script
                            
                            res.sendFile(__dirname + '/index.html');
                            

                            或指定一个根(用作res.sendFile()的第一个参数的基本路径:

                            res.sendFile('index.html', { root: __dirname });
                            

                            当您传递用户生成的文件路径时,指定root 路径更有用,该路径可能包含格式错误/恶意部分,如..(例如../../../../../../etc/passwd)。设置root 路径可防止此类恶意路径被用于访问该基本路径之外的文件。

                            【讨论】:

                            • 将根指定为上一级目录的最佳方法是什么?
                            • @SuperUberDuper 你的意思是像path.resolve(__dirname, '.../public')?这将解析为脚本父目录的“公共”子目录。
                            • 酷!将来会将此值永久存储在 __dirname 中吗?
                            • 嗨,我尝试了以下 res.sendFile(path.resolve(__dirname + '/index.html', '../')) 但收到消息:不能获取 /
                            • @SuperUberDuper ../../<etc> 类型语法进行导航。注意__dirname../public 之间的逗号。使用 + 号不起作用。
                            猜你喜欢
                            • 2022-12-26
                            • 2018-06-07
                            • 2015-04-17
                            • 2021-07-08
                            • 1970-01-01
                            • 1970-01-01
                            • 2023-01-12
                            • 1970-01-01
                            相关资源
                            最近更新 更多