HTTPS时,React截取/ auth / twitter /。我想从我的节点服务器访问/ auth / twitter /而不是反应应用程序

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HTTPS时,React截取/ auth / twitter /。我想从我的节点服务器访问/ auth / twitter /而不是反应应用程序相关的知识,希望对你有一定的参考价值。

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。

我已经尝试在misc位置添加http代理以及package.json并且无济于事我正在旋转我的轮子。

先感谢您。

身份验证路线

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());
      }
    });
  });
};
答案

您有一个服务工作者正在运行客户端并拦截请求,然后从它的缓存服务您的反应应用程序。

给出它的一个提示是服务工作者只能通过https https://developers.google.com/web/fundamentals/primers/service-workers/#you_need_https安装/运行

解决方案是编辑服务工作者代码,使其不能用于身份验证网址,或者如果您不打算在其周围构建应用程序,则将它们全部禁用,这可能比它的价值更麻烦。

以上是关于HTTPS时,React截取/ auth / twitter /。我想从我的节点服务器访问/ auth / twitter /而不是反应应用程序的主要内容,如果未能解决你的问题,请参考以下文章

Auth0 和 React 的 CORS 问题

在 next-auth 中制作自定义电子邮件登录页面时找不到“next-auth/react”模块

如何将 Auth0 与 react-admin 一起使用?

TW洞见|也谈响应式编程

React Hook SetState 导致无限循环

如何在浏览器中为 React SPA 保留 Auth0 登录状态