2017-11-10 9 views
1

Express 및 create-react-app을 사용하여 라우팅 작업을 수행하려고합니다.Express : 서브 루틴에서 정적 파일 제공

목표는 사용자가 URL이 / 일 때 응용 프로그램의 홈페이지로, URL이 /login 일 때 로그인 페이지로 이동하는 것입니다.

var express = require("express"); 
var path = require("path"); 

let router = express.Router(); 

router.route("/").get((req, res, next) => { 
    res.sendFile("index.html", { root: "./client/build/" }); 
}); 

router.route("/login").get((req, res, next) => { 
    res.send("This is the login page"); 
}); 

module.exports = router; 
: mainRoutes은 기본 탐색 (적어도이는 아이디어)에 대한 책임, apiRoutes 모든 API를 라우팅 정의를 포함

var mainRoutes = require("./routes/mainRoutes"); 
var apiRoutes = require("./routes/apiRoutes"); 

[...] 

app.use("/", mainRoutes); 
app.use("/api", apiRoutes); 

동안 내 server.js에서

나는 두 개의 경로가 정의되어

어디에서나 create-react-app 구축 프로세스에서 생성 된 정적 저작물에 대한 내용을 읽었으므로 다음을 추가했습니다.

// Priority serve any static files. 
app.use(express.static(path.join(__dirname, "client/build"))); 

// All remaining requests return the React app, so it can handle routing. 
app.get("*", function(req, res) { 
    res.sendFile(path.join(__dirname + "/client/build/index.html")); 
}); 

이 줄을 추가하면 매번 index.html을 볼 수 있지만 매회마다 기본 페이지 (index.html)로 리디렉션되기 때문에 /login/api 하위 루트를 방문 할 수 없습니다.

내 서브 루트 mainRoutes에 정적 파일을 제공해야하지만 그렇게하는 방법에 대한 아이디어가 없습니다.

어떻게하면됩니까?

답변

0

create-react-app 서버와 js를 사용하여 범용 라우팅을 수행하지 않는 한 하나의 페이지 응용 프로그램을 실행하기 때문에 원하는 라우팅 경로를 브라우저에서 처리 할 수 ​​없다고 생각합니다.

+0

그것은 HTML 페이지 라우팅처럼 작동하지 않습니다, 당신은 실제로 한 페이지를 실행 문자 그대로 c를 바꾼다. 호프 당신을 도울 것입니다 :> –

+0

"내 목표는 URL이/일 때 로그인 페이지 및/또는 로그인 페이지로 사용자를 응용 프로그램의 홈페이지로 안내하는 것입니다" url 사용자가 애플리케이션 또는 JS를 클릭하거나 브라우저에 입력 할 때마다 일치/로그인합니다. 현재 동작은 hashrouting을 사용하는 것이지만 반응 코드의 서버 렌더링을 통해 보편적 인 렌더링이나 보이지 않는 것처럼 보입니다. 둘 다 단점이 있지만 올바른 길로 인도 할 것이라고 생각합니다. 나는 아무것도 몰라 ..이 Q_Q 사람은 최대한 빨리 (express.static (path.join (__ dirname은 "클라이언트/빌드")는'app.use를 추가로에게 –

0

app.get('*')은 당신이하는 모든 단일 경로를 일치합니다 번들

당신은이 같은

해야 :.

var mainRoutes = require("./routes/mainRoutes"); 
var apiRoutes = require("./routes/apiRoutes"); 

[...] 

app.use(express.static(path.join(__dirname, "client/build"))); 

app.use("/", mainRoutes); 
app.use("/api", apiRoutes); 

// If the app reaches this point, it means that 
// the path did not match any of the ones above 
app.use(function(req, res, next){ 
    // redirect the user to where we serve the index.html 
    res.redirect('/'); 
}); 
+0

들을 위해 solutuion 사랑을 알고있는 경우));''/ login '페이지와'/ api' 경로를 방문 할 수 없습니다. 나는 항상 메인 어플리케이션으로 리다이렉트되었다. – Lc0rE