gpt4 book ai didi

javascript - 只有从根 url 启动时,React Router 才能进行路由

转载 作者:行者123 更新时间:2023-11-29 21:22:21 24 4
gpt4 key购买 nike

我有一个 React 应用程序,它也使用 Redux 和 ReactRouter。

我的问题如下:

当我启动应用程序并转到根 url 时,我可以正常在应用程序内部导航,并且导航栏中的路线会随着我的导航而变化。

但是,如果我在导航栏中输入除根以外的任何 url,我会收到一个奇怪的错误: enter image description here enter image description here

我真的不明白怎么会出现这样的错误。

如果我转到 localhost:1337/ 然后单击带有链接 /cars/1 的项目,一切都会很好,组件将成功呈现.如果我立即输入 localhost:1337/cars/1(或任何其他 existing 路由),我会收到此错误。

下面是我如何初始化 react-router 并定义我的路由:

index.js:

require('./style/style.css');

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import { Router, browserHistory } from 'react-router';
import reduxPromise from 'redux-promise';

import routes from './routes';
import reducers from './reducers';


const createStoreWithMiddleware = applyMiddleware(
reduxPromise
)(createStore);

ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<Router history={browserHistory} routes={routes} />
</Provider>
, document.querySelector('.container.app')
);

路由.js:

import React from 'react';
import { Route, IndexRoute, Redirect } from 'react-router';

import App from './components/app';
import CarsIndex from './containers/cars-index';
import CarNew from './containers/car-new';
import CarShow from './containers/car-show';
import CarEdit from './containers/car-edit';
import SignIn from './containers/signin';
import auth from './auth/auth';


function requireAuth(nextState, replace) {
if (!auth.loggedIn()) {
replace({
pathname: '/authenticate',
state: { nextPathname: nextState.location.pathname }
});
}
}

function filterLoggedIn(nextState, replace) {
if (auth.loggedIn()) {
replace({
pathname: '/',
state: { nextPathname: nextState.location.pathname }
});
}
}

export default (
<Route path='/' component={App}>
<IndexRoute component={CarsIndex} onEnter={requireAuth} />
<Route path='cars/new' component={CarNew} onEnter={requireAuth} />
<Route path='cars/:id' component={CarShow} onEnter={requireAuth} />
<Route path='cars/edit/:id' component={CarEdit} onEnter={requireAuth} />
<Route path='authenticate' component={SignIn} onEnter={filterLoggedIn} />
<Redirect from='*' to='/' />
</Route>
);

我的服务器是一个小型 express.js 应用程序,它将 /api/* 以外的任何请求重定向到 index.html 页面。

这是我的 server.js 的一部分:

const path = require('path');
const port = process.env.PORT || 1337;
const app = express();
const pathToStatic = path.join(__dirname, 'static');
express.static(path.join(__dirname, 'static'));
app.use(express.static(pathToStatic));
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.get('/api/cars', (req, res) => {
return Car.find((err, cars) => {
if (!err) {
return res.send(cars);
} else {
console.log(err);
res.statusCode = 500;
return res.send({ error: 'Server error' });
}
});
});
app.get('*', (req, res) => {
res.sendFile(path.resolve(pathToStatic, 'index.html'));
});

app.listen(port, () => {
console.log(`Express server is listening on port ${port}`);
});

你遇到过这样的问题吗?你能帮我找出解决这个问题的方法吗?

最佳答案

截图显示bundle.js (应要求)返回 index.html .

这是因为您的快速路线处理路线 api/cars然后将 所有内容 默认为 index.html。

当然,您所有出现在 index.html 上的资源也必须发送给浏览器。这包括 <script src="bundle.js"></script>浏览器一旦获得 index.html 就会请求它第一次。

因此,您必须有一些方法允许 express 处理对 index.html 的资源的请求。需要。

一个流行的解决方案是挂载一个 Assets 目录并将其放在默认路由之上。像这样的东西:

// api routes

app.use(express.static('assets'));

// default route

然后确保您的 bundle.js在 Assets 目录中。然后脚本标签看起来像 <script src="/assets/bundle.js"></script> .

关于javascript - 只有从根 url 启动时,React Router 才能进行路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38264075/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com