2014-09-27 15 views
80

[aggiungi] Quindi il mio prossimo problema è che quando provo ad aggiungere una nuova dipendenza (npm install --save socket. io). Anche il file JSON è valido. Ottengo questo errore: Impossibile analizzare JSONnode.js TypeError: path deve essere assoluto o specificare root a res.sendFile [non riuscito a analizzare 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 

(Non sono sicuro se questo è consentito su Stack Overflow, qualcuno per favore fatemelo sapere se la sua non)

Così ho cercato di capire perché questo errore è tornato. Tutti i file (HTML, JSON, JS) si trovano nella stessa cartella sul desktop. Sto usando node.js e socket.io (web developer New-ish, si prega di non essere troppo duro: p)

Questo è il mio file 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'); 
}); 

Questo è ciò che è Restituzione:

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) 

risposta

197

L'errore è abbastanza chiaro, è necessario specificare un assoluto (invece che relativo) percorso e/o impostare root nell'oggetto config per res.sendFile(). Esempi:

// assuming index.html is in the same directory as this script 

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

o specificare una radice (che viene utilizzato come il percorso di base per il primo argomento a res.sendFile():

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

specificando il percorso root è più utile quando si sta passando un dall'utente generato il percorso del file che potrebbe potenzialmente contenere parti malformate/dannose come .. (ad esempio ../../../../../../etc/passwd). L'impostazione del percorso root impedisce l'utilizzo di tali percorsi dannosi per accedere a file esterni a tale percorso di base

+1

qual è il modo migliore per specificare la radice come una directory? – SuperUberDuper

+1

@SuperUberDuper Intendi come 'path.resolve (__ dirname, '.../public')'? Ciò si risolverà nella sottodirectory "pubblica" della directory principale dello script. – mscdex

+0

cool! questo in futuro memorizza questo valore in __dirname? – SuperUberDuper

12

Provare ad aggiungere il percorso di root.

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

Grazie per la condivisione. – Kashif

2

Se si considera attendibile il percorso, path.resolve è un'opzione:

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')); 
    }); 
1

L'errore è abbastanza semplice. Molto probabilmente il motivo è che il tuo file index.html non si trova nella directory principale.

Oppure se si trova nella directory radice, il riferimento relativo non funziona.

Quindi è necessario indicare al server la posizione esatta del file. Questo potrebbe essere fatto usando il metodo dirname in NodeJs. Basta sostituire il codice con questo:

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

Assicurarsi che il aggiungere la barra "/" simbolo prima della tua home page. In caso contrario, il percorso diventerà: rootDirectoryindex.html

Mentre si desidera che sia: rootDirectory/index.html

0

Questo può essere risolto in un altro modo:

app.get("/", function(req, res){ 

    res.send(`${process.env.PWD}/index.html`) 

}); 

process.env.PWD sarà anteporre la directory di lavoro quando è stato avviato il processo.

2

in file .mjs che per ora non hanno __dirname

quindi

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