[node.js] res.sendFile 절대 경로

내가하면

res.sendfile('public/index1.html'); 

그런 다음 서버 콘솔 경고가 나타납니다.

더 이상 res.sendfile사용 되지 않는 표현 : res.sendFile대신 사용

그러나 클라이언트 측에서는 잘 작동합니다.

그러나 내가 그것을 바꿀 때

res.sendFile('public/index1.html');

오류가 발생합니다

TypeError : 경로는 절대적이거나 루트를 지정해야합니다 res.sendFile

index1.html렌더링되지 않습니다.

절대 경로가 무엇인지 알 수 없습니다. 나는이 public같은 수준에서 디렉토리를 server.js. 내가 뭐하는 거지 res.sendFile와에서 server.js. 나는 또한 선언했다app.use(express.static(path.join(__dirname, 'public')));

내 디렉토리 구조 추가 :

/Users/sj/test/
....app/
........models/
....public/
........index1.html

여기서 지정할 절대 경로는 무엇입니까?

Express 4.x를 사용하고 있습니다.



답변

express.static미들웨어는 분리되어 res.sendFile있으므로 절대 경로로 초기화 public에 아무것도하지 않습니다 디렉토리 res.sendFile. 와 직접 절대 경로를 사용해야합니다 res.sendFile. 이를 수행하는 두 가지 간단한 방법이 있습니다.

  1. res.sendFile(path.join(__dirname, '../public', 'index1.html'));
  2. res.sendFile('index1.html', { root: path.join(__dirname, '../public') });

참고 : __dirname 현재 실행중인 스크립트가있는 디렉토리를 반환합니다. 귀하의 경우 server.js는입니다 app/. 에 가려면 public먼저 한 수준을 되돌려 야합니다 ../public/index1.html.

참고 : 위의 코드가 작동하려면 path내장 모듈 이 필요합니다 require.var path = require('path');


답변

대신 이것을 시도하십시오 :

res.sendFile('public/index1.html' , { root : __dirname});

이것은 나를 위해 일했습니다. root : __ dirname은 위의 예제에서 server.js가있는 주소를 가져온 다음 index1.html (이 경우)에 도달하는 경로는 공용 폴더가있는 디렉토리로 이동하는 것입니다.


답변

res.sendFile( __dirname + "/public/" + "index1.html" );

여기서 __dirname현재 실행중인 스크립트 ( server.js) 가있는 디렉토리의 이름을 관리합니다 .


답변

아직 나열되지 않은 대안은 단순히 path.resolve별도의 문자열이나 전체 경로가있는 문자열을 사용하는 것입니다.

// comma separated
app.get('/', function(req, res) {
    res.sendFile( path.resolve('src', 'app', 'index.html') );
});

또는

// just one string with the path
app.get('/', function(req, res) {
    res.sendFile( path.resolve('src/app/index.html') );
});

(노드 v6.10.0)

아이디어는 https://stackoverflow.com/a/14594282/6189078에서 제공합니다.


답변

다른 답변을 바탕으로 가장 일반적인 요구 사항을 달성하는 방법에 대한 간단한 예입니다.

const app = express()
app.use(express.static('public')) // relative path of client-side code
app.get('*', function(req, res) {
    res.sendFile('index.html', { root: __dirname })
})
app.listen(process.env.PORT)

별표 를 사용 하여 정적 (공용) 디렉토리에없는 모든 파일을 포착 하기 때문에 이것은 모든 요청 에서 index.html응답 하는 간단한 방법으로도 두 배가됩니다 *. 웹앱의 가장 일반적인 사용 사례입니다. /루트 경로에서만 색인을 리턴하도록 변경하십시오 .


답변

나는 이것을 시도했고 효과가 있었다.

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


답변

process.cwd() 프로젝트의 절대 경로를 반환합니다.

그런 다음 :

res.sendFile( `${process.cwd()}/public/index1.html` );