如何在Ejected React Create App上配置响应头?

时间:2018-10-30 12:10:38

标签: reactjs cors webpack-dev-server http-proxy-middleware react-create-app

我正在尝试在我的项目中实现OAuth2流程。我有一个使用React-Create-App创建的仪表板应用程序,还有另一个使用React-Create-App创建的登录流程应用程序。另外,我还有一个springboot后端,用于处理授权和资源服务器部件。

所以我同时有3个不同的应用程序在工作,我将它们称为

申请流程

  1. 如果用户未登录到仪表板,我将重定向到登录应用程序
  2. 用户输入其电子邮件和密码
  3. 登录应用程序通过仪表板的重定向uri将请求发布到服务器(2884)
  4. 服务器重定向到仪表板

问题 当服务器发送重定向请求页面时,页面未重新加载,但返回了索引页面,即使ı可以在仪表板的Webpack上看到Option请求ı也不可以看到get请求,并且ı不能在代理中绕过它。 / p>

登录应用

getAuthorizationCode(userName, password) {
const headers = {
  'Content-Type': 'application/x-www-form-urlencoded',
};

return axios({
  url: 'http://localhost:2884/oauth/authorize',
  method: 'get',
  params: {
    scope: 'read',
    audience: 'tokyo',
    response_type: 'code',
    client_id: 'test_tokyo',
    redirect_uri: 'http://localhost:3000',
  },
  headers,
  auth: {
    username: userName,
    password: password,
  },
}).then((res) => {
  console.log('response', res); // I can see the index html at the console but page is not reloading
});

仪表板webpackDevServerConfig

module.exports = function(proxy, allowedHost) {
  return {
disableHostCheck:
  !proxy || process.env.DANGEROUSLY_DISABLE_HOST_CHECK === 'true',

compress: true,
clientLogLevel: 'none',
contentBase: paths.appPublic,
watchContentBase: true,
hot: true,
headers: {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Credentials': 'true',
  'Access-Control-Max-Age': '3600',
  'Access-Control-Allow-Headers': 'authorization',
  'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
},
proxy: {
  '/*': {
    target: {
      host: 'localhost',
      protocol: 'http',
      port: 3000,
    },
    secure: false,
    bypass(req, res) {
      console.info("Method = ", req.method);
      console.info("originalUrl = ", req.originalUrl);
      if (req.method === 'GET') {
        console.info("2");
        res.statusCode = 302;
        return 'a';
      }
      if (req.method === 'OPTIONS') {
        console.info("1");
        res.statusCode = 200;
        return 'a'; // I don't know the purpose of this line, but indeed it works
      }
    },
  },
},
publicPath: config.output.publicPath,
quiet: true,
watchOptions: {
  ignored: ignoredFiles(paths.appSrc),
},
https: protocol === 'https',
host: host,
overlay: false,
historyApiFallback: {
  disableDotRule: true,
},
public: allowedHost,
before(app) {
  app.use(errorOverlayMiddleware());
  app.use(noopServiceWorkerMiddleware());
},

网络流

1.Preflight Options Request From Login to Server

2.Original Get Request To Server

3.Preflight Options Request To Webpack of Dashboard

4.Original Get Request To Dashboard

我认为浏览器不会发送最后一个请求,因为ı在仪表板控制台上看不到它,但是ı可以看到第三个请求

0 个答案:

没有答案