特若网络 React react webpack配置代理

react webpack配置代理

最近在做一个react+spring的项目,要是同时调试前台和后台,查看了相关的资料,找到如下方法。 启动re…

最近在做一个react+spring的项目,要是同时调试前台和后台,查看了相关的资料,找到如下方法。

启动react前台调试后可以配置代理的方式指定后台服务的端口进行访问。

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

  // FIXME
  app.use(['/api/v3'], proxy({ target: 'http://localhost:8080/', changeOrigin: true }))
  app.use(['/image'], proxy({ target: 'http://localhost:8080/', changeOrigin: true }))
  app.use(['/api/test'], proxy({ target: 'http://localhost:8080/', changeOrigin: true }))
  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())
      }
    })
  })
}
/* eslint consistent-return:0 */

const express = require('express')
const logger = require('./logger')

const argv = require('./argv')
const port = require('./port')
const setup = require('./middlewares/frontendMiddleware')
const { resolve } = require('path')
const app = express()

// If you need a backend, e.g. an API, add your custom backend-specific middleware here
// app.use('/api', myApi);

// In production we need to pass these values in instead of relying on webpack
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'

// use the gzipped bundle
app.get('*.js', (req, res, next) => {
  req.url = req.url + '.gz' // eslint-disable-line
  res.set('Content-Encoding', 'gzip')
  next()
})

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

  logger.appStarted(port, prettyHost)
})

剩下的就是在package.json中配置执行脚本就可以了。

本文原创,禁止转载。https://www.gaojunxin.cn/2020/08/09/585/

作者: GJX

联系我们

联系我们

邮箱: gjx.xin@qq.com

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

关注微博
返回顶部