当使用HTTPS时,React会拦截/ auth / twitter /。我想从我的节点服务器访问/ auth / twitter /而不是react应用程序

时间:2018-12-07 21:44:34

标签: node.js reactjs session heroku proxy

React / Node的新手。

我有一个在Heroku的同一主机上运行的React(带有webpack等的React-boiler-plate)/ Node的实现。

我正在使用护照和推特宣誓会议。 当我命中端点http://example.heroku.com/auth/twitter/callback时,一切都会正常工作(以及运行本地开发服务器)。

当我尝试通过HTTPS https://example.heroku.com/auth/twitter/callback访问它时,React会拦截它并显示未找到页面。

我试图了解这种情况的发生原因,以及在类似“生产”环境中处理该问题的最佳方法。我想在同一主机上处理/ auth / twitter和/ auth / twitter / callback。

我尝试在杂项位置以及package.json中添加http代理,但无济于事,我正在转动轮子。

先谢谢您。

身份验证路由

module.exports = app => {
  app.get('/api/logout', (req, res) => {
    // Takes the cookie that contains the user ID and kills it - thats it
    req.logout();
    // res.redirect('/');
    res.send(false);
    // res.send({ response: 'logged out' });
  });
  app.get('/auth/twitter', passport.authenticate('twitter'));
  app.get(
    '/auth/twitter/callback',
    passport.authenticate('twitter', {
      failureRedirect: '/'
    }),
    (req, res) => {
      res.redirect('/dashboard');
    }
  );
  app.get('/api/current_user', (req, res) => {
    // res.send(req.session);
    // res.send({ response: req.user });
    res.send(req.user);
  });
};

index.js

app.use(morgan('combined'));
app.use(bodyParser.json());
app.use(
  //
  cookieSession({
    // Before automatically expired - 30 days in MS
    maxAge: 30 * 24 * 60 * 60 * 1000,
    keys: [keys.COOKIE_KEY]
  })
);
app.use(passport.initialize());
app.use(passport.session());

require('./routes/authRoutes')(app);
// They export a function - they turn into a function - then immediately call with express app object

app.use('/api/test', (req, res) => {
  res.json({ test: 'test' });
});

setup(app, {
  outputPath: resolve(process.cwd(), 'build'),
  publicPath: '/',
});

// get the intended host and port number, use localhost and port 3000 if not provided
const customHost = argv.host || process.env.HOST;
const host = customHost || null; // Let http.Server use its default IPv6/4 host
const prettyHost = customHost || 'localhost';

/ Start your app.
app.listen(port, host, async err => {
  if (err) {
    return logger.error(err.message);
  }

  // Connect to ngrok in dev mode
  if (ngrok) {
    let url;
    try {
      url = await ngrok.connect(port);
    } catch (e) {
      return logger.error(e);
    }
    logger.appStarted(port, prettyHost, url);
  } else {
    logger.appStarted(port, prettyHost);
  }
});

console.log('Server listening on:', port);




/**
 * Front-end middleware
 */
module.exports = (app, options) => {
  const isProd = process.env.NODE_ENV === 'production';
  if (isProd) {
    const addProdMiddlewares = require('./addProdMiddlewares');
    addProdMiddlewares(app, options);
  } else {
    const webpackConfig = require('../../internals/webpack/webpack.dev.babel');
    const addDevMiddlewares = require('./addDevMiddlewares');
    addDevMiddlewares(app, webpackConfig);
  }

  return app;
};

const path = require('path');
const express = require('express');
const compression = require('compression');

module.exports = function addProdMiddlewares(app, options) {
  // messing around here 
  const proxy = require('http-proxy-middleware');
  const apiProxy = proxy('/api', { target: 'http://localhost:3000' });
  const apiProxy2 = proxy('/auth', { target: 'http://localhost:3000' });
  app.use('/api', apiProxy);
  app.use('/auth/*', apiProxy2);
  const publicPath = options.publicPath || '/';
  const outputPath = options.outputPath || path.resolve(process.cwd(), 'build');

  // compression middleware compresses your server responses which makes them
  // smaller (applies also to assets). You can read more about that technique
  // and other good practices on official Express.js docs http://mxs.is/googmy
  app.use(compression());
  app.use(publicPath, express.static(outputPath));

  app.get('*', (req, res) =>
    res.sendFile(path.resolve(outputPath, 'index.html')),
  );
};

const path = require('path');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');

function createWebpackMiddleware(compiler, publicPath) {
  return webpackDevMiddleware(compiler, {
    logLevel: 'warn',
    publicPath,
    silent: true,
    stats: 'errors-only',
  });
}

module.exports = function addDevMiddlewares(app, webpackConfig) {
  const compiler = webpack(webpackConfig);
  const middleware = createWebpackMiddleware(
    compiler,
    webpackConfig.output.publicPath,
  );

  app.use(middleware);
  app.use(webpackHotMiddleware(compiler));

  // Since webpackDevMiddleware uses memory-fs internally to store build
  // artifacts, we use it instead
  const fs = middleware.fileSystem;

  app.get('*', (req, res) => {
    fs.readFile(path.join(compiler.outputPath, 'index.html'), (err, file) => {
      if (err) {
        res.sendStatus(404);
      } else {
        res.send(file.toString());
      }
    });
  });
};

1 个答案:

答案 0 :(得分:1)

您有一个服务工作者正在运行客户端并拦截请求,然后从其缓存中为您的react应用服务。

一个可以忽略的提示是,将仅在https https://developers.google.com/web/fundamentals/primers/service-workers/#you_need_https上安装/运行Service Worker

解决方案是编辑服务工作者代码以使其不用于身份验证url,或者如果您不打算围绕它构建应用程序,则将其全部禁用,这可能比其价值更大。 / p>