IT박스

node.js TypeError : 경로는 절대적이거나 res.sendFile에 루트를 지정해야합니다 [JSON 구문 분석에 실패했습니다]

itboxs 2020. 6. 28. 19:23
반응형

node.js TypeError : 경로는 절대적이거나 res.sendFile에 루트를 지정해야합니다 [JSON 구문 분석에 실패했습니다]


[add] 그래서 다음 문제는 새로운 의존성 (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)

오류는 매우 분명합니다. 상대 경로 대신 절대 경로를 지정하거나 root에 대한 구성 객체에서 설정해야합니다 res.sendFile(). 예 :

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

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

또는 루트를 지정하십시오 (이는 첫 번째 인수의 기본 경로로 사용됩니다 res.sendFile():

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

Specifying the root path is more useful when you're passing a user-generated file path which could potentially contain malformed/malicious parts like .. (e.g. ../../../../../../etc/passwd). Setting the root path prevents such malicious paths from being used to access files outside of that base path.


Try adding root path.

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

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

hence

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

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

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


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

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


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

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

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

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.


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

참고URL : https://stackoverflow.com/questions/26079611/node-js-typeerror-path-must-be-absolute-or-specify-root-to-res-sendfile-failed

반응형