301使用Webpack开发服务器重定向

rkttyhzu  于 2022-11-13  发布在  Webpack
关注(0)|答案(2)|浏览(203)

我正在尝试重定向此格式的URL:
http://localhost:8080/setup/xyz/?code=some-code
更改为:
http://localhost:8080/app/#/setup/xyz/?code=some-code
我尝试过代理和重写:

historyApiFallback: {
  rewrites: [
    { from: /^\/$/, to: '/index.html' },
    { from: /^\/app/, to: '/app.html' },
    { from: /^\/setup/, to: '/app/#/setup' },
  ]

},
但是它似乎不起作用。有没有办法用dev服务器来写301重定向?

zphenhs4

zphenhs41#

尝试配置devServerhttps://itsopensource.com/how-to-serve-api-locally-with-webpack/

const data = require("./data.json");

module.exports = {
  mode: "development",
  entry: "./src/index",
  output: {
    filename: "bundle.js",
    path: path.resolve(__dirname, "build")
  },
  plugins: [],
  devServer: {
    before: function(app) {
      app.get("/getData", function(req, res) {
        res.json(data);
      });
    },
    open: true,
    port: 3000
  },
  resolve: {
    extensions: [".js"]
  },
  module: {}
};
bmp9r5qi

bmp9r5qi2#

@Eugen的回答让我走上了正确的道路。以下是我需要的额外细节:
当前的devserver API是onBeforeSetupMiddleware,它公开了express server API,包括重定向。

devServer: {
    onBeforeSetupMiddleware: (devServer) => {
      devServer?.app?.get('/setup', (req, res) => {
        res.redirect('/app/#' + req.originalUrl);
      });
    }
  },

相关问题