简体   繁体   English

如何使用webpack代理devserver pathRewrite?

[英]How to use webpack proxy devserver pathRewrite?

I'm currently struggling with rewriting the proxy path to the api server. 我目前正在努力将代理路径重写为api服务器。 In my setup what I do is for api request, I delegate it to the proxy server and only for js/html/css webpack-dev-server is used. 在我的设置中,我对api请求的处理是将其委托给代理服务器,并且仅用于js / html / css webpack-dev-server

Following is what I'm using: 以下是我正在使用的:

devServer: {
    inline: true,
    port: 8080,
    historyApiFallback: true,
    publicPath: 'http://localhost:8080/dist/',
    disableHostCheck: true,
    proxy: {
        '/api': {
        target: 'http://localhost:3000',
        pathRewrite: {'???' : ''} //Need to append http://localhost:3000/MySite1/api
  }
}

So, How do I append /MySite1 to api request before it proxies to the localhost:3000? 那么,如何在代理请求/ localhost之前将/ MySite1附加到api请求?

Eg If the request is : http://localhost:8080/api , it should re write to http://localhost:3000/MySite1/api 例如,如果请求为: http:// localhost:8080 / api ,则应重新写入http:// localhost:3000 / MySite1 / api

Also, If the request is : http://localhost:8080 , it should re write to http://localhost:3000/MySite1 此外,如果请求为: http:// localhost:8080 ,则应将其重新写入http:// localhost:3000 / MySite1

Try following: 请尝试以下操作:

devServer: {
inline: true,
port: 8080,
historyApiFallback: true,
publicPath: 'http://localhost:8080/dist/',
disableHostCheck: true,
proxy: {
     '/api': {
     target: 'http://localhost:3000',
      pathRewrite: function(path, req) {
       var replacedPath = path;
       if (path.indexOf("MySite1") === -1) {
         replacedPath = replacedPath.replace("/", "/MySite1/api/");
       }
       return replacedPath;
     },
  }
}

Create proxy.config.json 创建proxy.config.json

{
  "/api/*": {
    "target": "http://localhost:3000/MySite1/api",
    "pathRewrite": {
      "^/api": ""
    },
    "changeOrigin": true,
    "secure": false,
    "logLevel": "debug"
  }
}

the ^/api part will be replaced with target ^ / api部分将替换为目标

and then start the app with 然后使用

ng serve --proxy-config proxy.config.json

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

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