node.js TypeError: path must be absolute or specify root to res.sendFile [failed to parse JSON]

前端 未结 13 1748
长情又很酷
长情又很酷 2020-11-28 20:03

[add] So my next problem is that when i try adding a new dependence (npm install --save socket.io). The JSON file is also valid. I get this error: Failed to parse json

相关标签:
13条回答
  • 2020-11-28 20:12

    The error is pretty straightforward. Most likely the reason is that your index.html file is not in the root directory.

    Or if it is in the root directory then the relative referencing is not working.

    So you need to tell the server exact location of your file. This could be done by using dirname method in NodeJs. Just replace your code with this one:

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

    Make sure that your add the slash "/" symbol before your homepage. Otherwise your path will become: rootDirectoryindex.html

    Whereas you want it to be: rootDirectory/index.html

    0 讨论(0)
  • 2020-11-28 20:14

    in .mjs files we for now don't have __dirname

    hence

    res.sendFile('index.html', { root: '.' })
    
    0 讨论(0)
  • 2020-11-28 20:19

    This can be resolved in another way:

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

    process.env.PWD will prepend the working directory when the process was started.

    0 讨论(0)
  • 2020-11-28 20:21

    In Typescript with relative path to the icon:

    import path from 'path';
    
    route.get('/favicon.ico', (_req, res) => res.sendFile(path.join(__dirname, '../static/myicon.png')));
    
    0 讨论(0)
  • 2020-11-28 20:23

    If you trust the path, path.resolve is an option:

    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'));
        });
    
    0 讨论(0)
  • 2020-11-28 20:31

    You might consider using double slashes on your directory e.g

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

    0 讨论(0)
提交回复
热议问题