路由在开发服务器(localhost)上有效,但在服务器上的生产版本中无效

时间:2019-03-29 18:30:25

标签: reactjs react-router

当我尝试部署到实际的网络磁盘时,我已经做好了所有准备工作,并在开发服务器上工作,组件根本没有呈现。

控制台上没有任何内容,但是picArray状态已更新为来自后端的信息。

基本上可以在这些图像上看到发生的情况:第一个图像(本地主机/开发服务器)正在呈现Login组件,而在第二个图像(已上载至服务器)中根本没有呈现Login组件。

localhost server

我不知道这里发生了什么,所以我决定寻求帮助。 我已经包含了app.js,Login.js的代码,因为它是索引。我还包括了package.json。

我尝试的方法:我尝试在没有路由器基本名称的情况下进行构建,将确切的地址和路径添加到package.json的“首页”,并在路由路径上尝试使用一些不同的语法。

app.js

import React, {Component} from 'react';
import {BrowserRouter as Router, Route} from 'react-router-dom';
import './App.css';
import {getAllMedia} from './utils/MediaAPI';
import Nav from './components/Nav';
import Home from './views/Home';
import Profile from './views/Profile';
import Single from './views/Single';
import Login from './views/Login';
import {tokenCheck} from './utils/MediaAPI';
import PropTypes from 'prop-types';
import {Redirect} from 'react-router';

class App extends Component {
  state = {
    picArray: [],
    user: [],
  };

  componentDidMount() {
    getAllMedia().then(pics => {
      this.setState({picArray: pics});
    });
    tokenCheck(localStorage.getItem('Login-token')).then(data => {
      if (data.message) {
        this.setState({errorMessage: data.message});
      } else {
        this.setState({user: data});
        this.setState({errorMessage: ''});
      }
    });
  }

  setUser = (data) => {
    this.setState({user: data});
    localStorage.setItem('Login-token', data.token);
    this.setState({errorMessage: ''});
  };

  logout = () => {
    this.setState({user: ''});
    localStorage.clear();
    tokenCheck(localStorage.getItem('Login-token')).then(data => {
      this.setState({errorMessage: data.message});
    });
    return <Redirect to='/'/>;
  };

  render() {
    return (
        <div id='container'>
          <Router basename="/~juhoh/testbuild">
            {!this.state.errorMessage && <Nav/>}
            <Route exact path="/" render={(props) => (
                <Login {...props} setUser={this.setUser}/>
            )}/>
            <Route exact path="/home" render={(props) => (
                <Home {...props} picArray={this.state.picArray}/>
            )}/>
            <Route exact path="/profile" render={(props) => (
                <Profile {...props} userData={this.state.user}/>
            )}/>
            <Route exact path="/single/:id" component={Single}/>
            <Route exact path="/logout" component={this.logout}/>
          </Router>
        </div>
    );
  }
}

App.propTypes = {
  history: PropTypes.object,
};

export default App;

Login.js

import React, {Component} from 'react';
import {login, tokenCheck} from '../utils/MediaAPI';
import PropTypes from 'prop-types';
import {registerUser} from '../utils/MediaAPI';
import {checkIfUserNameExists} from '../utils/MediaAPI';

class Login extends Component {
  state = {
    username: '',
    password: '',
    email: '',
    full_name: '',
  };

  componentDidMount() {
    tokenCheck(localStorage.getItem('Login-token')).then(data => {
      if (data.message) {
        console.log('No token found. No redirection needed.');
      } else {
        this.props.history.push('/home');
      }
    });
  }

  handleInputChange = (evt) => {
    const target = evt.target;
    const value = target.value;
    const name = target.name;
    //console.log(name, value);
    this.setState({
      [name]: value,
    });
  };

  login = (evt) => {
    evt.preventDefault();
    login(this.state.username, this.state.password).then((user) => {
      if (user.token) {
        this.props.setUser(user);
        this.props.history.push('/home');
      } else {
        window.alert(user.message);
      }
    });
  };

  register = (evt) => {
    evt.preventDefault();
    checkIfUserNameExists(this.state.username).then((isAvailable) => {
      if (isAvailable.available === true) {
        registerUser(this.state.username, this.state.password,
            this.state.full_name, this.state.email).then((data) => {
          if (data.error) {
            window.alert(data.message + '\n' + data.error);
          } else {
            this.login(evt);
            window.alert(data.message + '\nLogging in...');
          }
        });
      } else {
        window.alert('username not available');
      }
    });
  };

  render() {
    return (
        <React.Fragment>
          <h1>Login</h1>
          <form onSubmit={this.login}>
            <input type="text" name="username" placeholder="username"
                   value={this.state.username}
                   onChange={this.handleInputChange}/>

            <input type="password" name="password" placeholder="password"
                   value={this.state.password}
                   onChange={this.handleInputChange}/>

            <button type="submit">Login</button>

          </form>
          <br/>

          <h1>Register</h1>
          <form onSubmit={this.register}>
            <input type="text" name="username" placeholder="username"
                   value={this.state.username}
                   onChange={this.handleInputChange}/>

            <input type="password" name="password" placeholder="password"
                   value={this.state.password}
                   onChange={this.handleInputChange}/>

            <br/>

            <input type="text" name="full_name" placeholder="fullname"
                   value={this.state.full_name}
                   onChange={this.handleInputChange}/>

            <input type="text" name="email" placeholder="email"
                   value={this.state.email}
                   onChange={this.handleInputChange}/>

            <button type="submit">Register</button>

          </form>
        </React.Fragment>
    );
  }
}

Login.propTypes = {
  setUser: PropTypes.func,
  history: PropTypes.object,
};

export default Login;

package.json

{
  "name": "my-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^16.8.4",
    "react-dom": "^16.8.4",
    "react-router-dom": "^5.0.0",
    "react-scripts": "2.1.8"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ],
  "devDependencies": {
    "eslint": "5.12.0",
    "eslint-config-google": "^0.12.0",
    "eslint-plugin-react": "^7.12.4"
  },
  "homepage": "."
}

1 个答案:

答案 0 :(得分:-2)

我假设您没有使用哈希路由器。您可以尝试使用此方法代替浏览器路由器,这样可以解决此问题。另外,您可以使用某种后端来解决此问题。