简体   繁体   English

如何在Create React App中使用Webpack devServer代理

[英]How to use webpack devServer proxy in create react app

I'm creating a new app by using create-react-app and I want to add some proxies for my code. 我正在使用create-react-app创建一个新应用,我想为我的代码添加一些代理。 Previously I have used webpacks devServer 以前我使用过webpacks devServer

module.exports = {
  ...
  devServer: {
    proxy: {
      '/api/context*': {
        target: 'http://some.endpoint.com',
        headers: myCustomerHeaders,
        pathRewrite: (path, res) => changeThePath
      }
    }
  }
  ...
}

I have tried using the same approach in both webpack.config.dev.js and the webpackDevServer.config.js as well as putting it start.js as proxyConfig that is being passed to the webpackDevServer.config.js. 我已经尝试在webpack.config.dev.js和webpackDevServer.config.js中使用相同的方法,并将start.js作为proxyConfig传递给webpackDevServer.config.js。

I see writings of src/setupProxy.js but is it applicable without expressJs running somewhere? 我看到了src / setupProxy.js的著作,但是如果expressJs不在某个地方运行,它是否适用? Anyway I tried it without any result. 无论如何,我尝试了一下却没有任何结果。 The paths I'm proxying to are test environment api's that I wish to use. 我要代理的路径是我希望使用的测试环境api。

I have used create-react-app as a new skeleton for an old application to upgrade it, my old project works with the proxy settings. 我已经使用create-react-app作为旧应用程序的新框架来升级它,我的旧项目可以使用代理设置。

Now that I'm using create-react-app, I expected the same way be plausible, but it seems I am wrong. 既然我正在使用create-react-app,我期望同样的方法是合理的,但似乎我是错的。 Any takers of what I am doing wrong? 有人认为我做错了吗?

You can use "http-proxy-middleware" 您可以使用“ http-proxy-middleware”

https://github.com/chimurai/http-proxy-middleware https://github.com/chimurai/http-proxy-middleware

var express = require('express')
var proxy = require('http-proxy-middleware')

var app = express()

app.use('/api', proxy({ target: 'http://www.example.org', changeOrigin: true }))
app.listen(3000)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM