리액트 라우터 v4 - GET할 수 없음 *url*
리액트 라우터 v4를 사용하기 시작했습니다.심플한 게 있어요<Router>
(아래 코드 참조)로 이동합니다.로 이동하면localhost/vocabulary
라우터는 오른쪽 페이지로 리다이렉트 합니다.다만, 그 후에 새로고침(F5)을 눌렀을 때(localhost/vocabulary
모든 콘텐츠가 사라지고 브라우저 보고서가 나타납니다.Cannot GET /vocabulary
.어떻게 그것이 가능한가요?누가 그 문제(페이지 새로고침)를 해결하는 방법을 가르쳐 줄 수 있나요?
App.js:
import React from 'react'
import ReactDOM from 'react-dom'
import { BrowserRouter as Router, Route, Link } from 'react-router-dom'
import { Switch, Redirect } from 'react-router'
import Login from './pages/Login'
import Vocabulary from './pages/Vocabulary'
const appContainer = document.getElementById('app')
ReactDOM.render(
<Router>
<div>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/vocabulary">Vocabulary</Link></li>
</ul>
<Switch>
<Route exact path="/" component={Login} />
<Route exact path="/vocabulary" component={Vocabulary} />
</Switch>
</div>
</Router>,
appContainer)
웹팩을 사용하시겠죠?이 경우 웹 팩 구성에 몇 가지 사항을 추가하면 문제가 해결됩니다.구체적으로는output.publicPath = '/'
그리고.devServer.historyApiFallback = true
다음은 ^를 모두 사용하여 새로 고침 문제를 수정하는 웹 팩 구성 예입니다.'왜'가 궁금하다면 이게 도움이 될 거예요.
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './app/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index_bundle.js',
publicPath: '/'
},
module: {
rules: [
{ test: /\.(js)$/, use: 'babel-loader' },
{ test: /\.css$/, use: [ 'style-loader', 'css-loader' ]}
]
},
devServer: {
historyApiFallback: true,
},
plugins: [
new HtmlWebpackPlugin({
template: 'app/index.html'
})
]
};
자세한 내용은 여기에 기재했습니다.React Router를 사용하여 새로 고칠 때 "Cannot GET /URL" 오류 수정(또는 클라이언트 측 라우터의 작동 방식)
타일러의 답변을 보충하기 위해 아직 어려움을 겪고 있는 분들을 위해:
추가devServer.historyApiFallback: true
(설정하지 않고) WebPack Configuration으로 이행합니다.publicPath
)에서 발생한 404/Cannot-GET 오류는 리프레시/백/포워드에서 수정되었지만 네스트된 루트의 단일 레벨에서만 수정되었습니다.즉, "/"와 "/topics"는 정상적으로 동작하기 시작했지만, 그 이외의 것("/topics/whate" 등)은 리프레시(refresh)로 404를 계속 점등하고 있습니다.
여기서 방금 받아들인 답변이 나왔습니다.리액트 라우터 컴포넌트에서 예기치 않은 토큰< 에러가 발생했습니다.이것에 의해, 나에게 있어서 마지막이 없어졌습니다.선두 추가/
번들 스크립트 src로 이동합니다.index.html
이 문제를 완전히 해결했습니다.
난 그냥 덧셈만 하면 돼devServer { historyApiFallback: true }
사용할 필요가 없습니다.publicPath: '/'
용도:
devServer: {
historyApiFallback: true
},
애플리케이션이 스태틱파일 서버상에서 호스트 되고 있는 경우는, 대신에 를 사용할 필요가 있습니다.
import { HashRouter } from 'react-router-dom'
ReactDOM.render((
<HashRouter>
<App />
</HashRouter>
), holder)
저도 같은 문제를 겪고 있었는데 그걸 고친 건 제 편집이었어요package.json
파일 및 아래scripts: {
"build": "webpack -d && copy src\\index.html dist\\index.html /y && webpack-dev-server --content-base src --inline --port 3000"
웹 팩의 마지막에build
추가한 코드--history-api-fallback
이것은 또한 가장 쉬운 해결책으로 보였다.Cannot GET /url
에러
주의: 추가 후 다음 빌드 시--history-api-fallback
출력에 다음과 같은 행이 표시됩니다(인덱스 파일에 관계없이).
404s는 /index.dell에 폴백합니다.
Express(Webpack이 아닌)를 사용하는 경우에는 이 방법이 도움이 되었습니다.
app.get('/*', function(req, res) {
res.sendFile(path.join(__dirname, 'path/to/your/index.html'), function(err) {
if (err) {
res.status(500).send(err)
}
})
})
v6에서의 (Webpack 5의 )
(https://webpack.js.org/configuration/dev-server/ #devservermagichtml):
devServer: {
magicHtml: true,
historyApiFallback: true,
},
plugins: [
new HtmlWebpackPlugin({
template: path.resolve(__dirname, 'src/index.html'),
publicPath: '/',
})
]
을을... historyApiFallback: true
devServer: {
contentBase: path.join(__dirname, "public"),
watchContentBase: true,
publicPath: "/dist/",
historyApiFallback: true
}
웹 팩을 사용하는 경우 서버 구성의 일부에서 "contentBase" 속성에 대한 구성을 확인합니다.다음의 예에 의해서 설정할 수 있습니다.
devServer: {
...
contentBase: path.join(__dirname, '../')
...
}
)HtmlWebpackPlugin
하고 있는 경우는, 「에러」를 합니다.filename
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★filename
에는 특별히 .filename
에 맡기다WEBPACK_DEV_SERVER
해 주세요.아래 예를 참조하십시오.
new HtmlWebpackPlugin({
template: './src/index.html',
filename: process.env.WEBPACK_DEV_SERVER ? 'index.html' : PROD_HTML_PATH,
})
If you are using webpack. You need to add
devServer: {
historyApiFallback: true,
}
Example ::
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './app/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index_bundle.js',
publicPath: '/'
},
module: {
rules: [
{ test: /\.(js)$/, use: 'babel-loader' },
{ test: /\.css$/, use: [ 'style-loader', 'css-loader' ]}
]
},
devServer: {
historyApiFallback: true,
},
plugins: [
new HtmlWebpackPlugin({
template: 'app/index.html'
})
]
};
언급URL : https://stackoverflow.com/questions/43209666/react-router-v4-cannot-get-url
'source' 카테고리의 다른 글
포스트그레스 JSON 인덱스는 기존의 정규화 테이블에 비해 효율이 충분히 높은가요? (0) | 2023.02.26 |
---|---|
ResponseEntity를 사용하여 InputStream을 닫는 적절한 스트리밍 방법 (0) | 2023.02.26 |
Zuul 예외 사용자 지정 (0) | 2023.02.26 |
날짜별로 MongoDB ObjectId를 조회할 수 있습니까? (0) | 2023.02.26 |
사용자 지정 게시 유형을 표시하는 워드프레스 검색 중지 (0) | 2023.02.26 |