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

前端 未结 13 1747
长情又很酷
长情又很酷 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:07

    Try adding root path.

    app.get('/', function(req, res) {
        res.sendFile('index.html', { root: __dirname });
    });
    
    0 讨论(0)
  • 2020-11-28 20:08

    I solve this by using path variable. The sample code will look like below.

    var path = require("path");
    
    app.get('/', (req, res) => {
        res.sendFile(path.join(__dirname + '/index.html'));
    })
    
    0 讨论(0)
  • 2020-11-28 20:09

    It will redirects to index.html on localhost:8080 call.

    app.get('/',function(req,res){
        res.sendFile('index.html', { root: __dirname });
    });
    
    0 讨论(0)
  • 2020-11-28 20:09

    I used the code below and tried to show the sitemap.xml file

    router.get('/sitemap.xml', function (req, res) {
        res.sendFile('sitemap.xml', { root: '.' });
    });
    
    0 讨论(0)
  • 2020-11-28 20:11

    If you are working on Root Directory then you can use this approach

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

    but if you are using Routes which is inside a folder lets say /Routes/someRoute.js then you will need to do something like this

    const path = require("path");
    ...
    route.get("/some_route", (req, res) => {
       res.sendFile(path.resolve('FOLDER_IN_ROOT_DIRECTORY/index.html')
    });
    
    
    0 讨论(0)
  • 2020-11-28 20:11

    I did this and now my app is working properly,

    res.sendFile('your drive://your_subfolders//file.html');
    
    0 讨论(0)
提交回复
热议问题