ReactJS + NodeJS:如何为应用程序和API分隔路由?

时间:2018-10-30 18:18:20

标签: node.js reactjs api router

我有一个React应用,NodeJS后端。我很难将网站应用程序的路由(例如website.com/homewebsite.com/about)和URL(包含JSON数据的端点)(例如website.com/v1/userswebsite.com/v1/tournaments)分开

这是我的app.js

const PORT = process.env.PORT || 5000;
const env = process.env.NODE_ENV || 'development';

const express = require('express'),
      path = require('path'),
      mongoose = require('mongoose'),
      bodyParser = require('body-parser'),
      passport = require('passport');

const config = require('./backend/config/db')[env]; // load db
mongoose.connect(config.DB, { useNewUrlParser: true }).then(
    () => {console.log('Database is connected') },
    err => { console.log('Can not connect to the database'+ err)}
);

const users = require('./backend/routes/user'); 
const v1 = require('./backend/routes/v1'); 

const app = express();

// Serve static files from the React app -- added because of Heroku, the local app doesn't need this
app.use(express.static(path.join(__dirname, 'frontend/build')));


app.use(passport.initialize());
require('./backend/passport')(passport);

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// routes
app.use('/api/users', users);
app.use('/v1', v1);

app.get('/', function(req, res) {
    res.send('hello');
});

app.listen(PORT, () => {
    console.log(`Server is running on PORT ${PORT}`);
});

然后,在React前端文件夹中,我有一个看起来像这样的文件App.js

// react logic
import React, { Component } from 'react';
import { BrowserRouter as Router, Route } from 'react-router-dom';

// redus
import { Provider } from 'react-redux';
import store from './redux/store';

// authentication
import jwt_decode from 'jwt-decode';
import setAuthToken from './setAuthToken';
import { setCurrentUser, logoutUser } from './redux/actions/authentication';

// pages
import Navbar from './components/Navbar';
import Register from './components/Register';
import Login from './components/Login';
import Home from './components/Home';
import About from './components/About';
//import ApiV1 from './components/ApiV1';

// css
import 'bootstrap/dist/css/bootstrap.min.css';

if(localStorage.jwtToken) {
  setAuthToken(localStorage.jwtToken);
  const decoded = jwt_decode(localStorage.jwtToken);
  store.dispatch(setCurrentUser(decoded));

  const currentTime = Date.now() / 1000;
  if(decoded.exp < currentTime) {
    store.dispatch(logoutUser());
    window.location.href = '/login'
  }
}

export default class App extends Component {
    render() {
      return (
          <Provider store = { store }>
            <Router>
              <div>
                <Navbar />
                <Route exact path="/" component={ Home } />
                <div className="container">
                    <Route exact path="/home" component={ Home } />
                    <Route exact path="/about" component={ About } />
                    {/* <Route exact path="/v1" component={ ApiV1 } /> */}
                </div>
              </div>
            </Router>
          </Provider>
        );
    }
}

当我将浏览器的URL website.com/v1/users放到浏览器中时,我看到的只是一个React前端布局,而不是包含数据库中数据的JSON文件。

我该如何修改路由/节点的app.js文件来实现这一目标?

谢谢。

编辑:

backend/routes/v1.js

const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const passport = require('passport');

const User = require('../models/User');

passport.serializeUser(function(user, done) {
    done(null, user);
});
passport.deserializeUser(function(user, done) {
    done(null, user);
});

router.get('/v1', passport.authenticate('jwt'), function(req, res, next) {
    console.log('in /v1');

    User.find({}).sort('-createdAt').exec(function(err, fetched_users) {
        if(err) throw err;
        let users = {
            users: fetched_users
        };
        res.json(users);
    });    
});

module.exports = router;

0 个答案:

没有答案