expressjs保护的路由和react-router路由相同的URL不起作用

时间:2018-07-13 05:48:35

标签: javascript node.js reactjs express react-router

-我创建了一个类似/ product-list /的链接,需要登录才能在我的服务器中看到快递... 但是我的react-router中有一个类似/ product-list /的链接....

如果我不刷新浏览器,则此受保护的链接/ product-list不需要登录 我如何解决此错误,如何对expressjs进行身份验证和对React-Router进行协同工作。

此处是我的react-router代码:

import React from 'react';
import HomePage from './Pages/HomePage/HomePage';
import NotFoundPage from './Pages/NotFoundPage/NotFoundPage';
import ProductListPage from './Pages/ProductListPage/ProductListPage';
import ProductActionContainer from './Containers/ProductActionContainer';


const routes = [
    {
        path: '/',
        exact: true,
        main: () => <HomePage />
    },
    {
        path: '/Product-List',
        exact: true,
        main: () => <ProductListPage />
    },
    {
        path: '/product/add',
        exact: false,
        main: ({ match }) => <ProductActionContainer match={match} />
    },
    {
        path: '/product/:id/edit',
        exact: false,
        main: ({ match }) => <ProductActionContainer match={match} />
    },
    {
        path: '',
        exact: false,
        main: () => <NotFoundPage />
    }

];

export default routes;

这是服务器代码:

var path = require("path");
var bodyParser = require('body-parser');
var passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const session = require('express-session');
const logger = require('morgan');

var express = require('express');
var app = express();
var router = express.Router();


app.use(logger('tiny'));
app.set('views', 'C:/Users/nguyen_tien_nghiep/Desktop/test/react-api-webpack/src/views');
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, '..', '/dist')));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(session({
    secret: 'asfasfasl',
    resave: true,
    saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());

app.use('/', router);



router.get('/', function (req, res) {
    res.render('index');
});

router.post('/', passport.authenticate('local', { successRedirect: '/product-list', failureRedirect: '/login' }));

router.get('/product-list', (req, res) => {
    if (req.isAuthenticated()) {
        // res.rend('index');
    }
    else {
        res.redirect('/');
    }

});

passport.use(new LocalStrategy((username, password, done) => {
    var user = { usr: 'test', pwd: 'test' };
    const userRecord = user.usr === username ? username : null;
    if (userRecord && password === user.pwd) {
        return done(null, userRecord);
    }
    else {
        return done(null, false);
    }
}));

passport.serializeUser((name, done) => {
    done(null, name);
});

passport.deserializeUser((name, done) => {
    var user = { usr: 'test', pwd: 'test' };
    if (name === user.usr) {
        return done(null, user);
    }
    else {
        return done(null, false);
    }
});

app.listen(8081);

0 个答案:

没有答案