Christian-health / StudyNote2017

2017年学习笔记
0 stars 0 forks source link

angular cli 学习笔记 #9

Open Christian-health opened 6 years ago

Christian-health commented 6 years ago

Proxy To Backend 后台代理

Using the proxying support in webpack's dev server we can highjack certain urls and send them to a backend server. We do this by passing a file to --proxy-config 在webpack的dev服务器中使用代理支持,我们可以高速缓存某些url并将其发送到后端服务器。 我们通过将文件传递给--proxy-config来执行此操作

Say we have a server running on http://localhost:3000/api and we want all calls to http://localhost:4200/api to go to that server. 假设我们有一个运行在 http://localhost:3000/api 上的服务器,我们希望所有调用http://localhost:4200/api都可以访问该服务器。

We create a file next to projects package.json called proxy.conf.json with the content 我们在项目package.json旁边创建一个名为proxy.conf.json的文件

{
  "/api": {
    "target": "http://localhost:3000",
    "secure": false
  }
}

You can read more about what options are available here webpack-dev-server proxy settings 您可以在这里阅读更多关于webpack-dev-server代理设置的可用选项

然后我们编辑package.json文件的start脚本 and then we edit the package.json file's start script to be

"start": "ng serve --proxy-config proxy.conf.json",

now run it with npm start 现在运行npm

Multiple entries 多个入口

If you need to proxy multiple entries to the same target define the configuration in proxy.conf.js e.g. 如果需要将多个入口代理到同一目标,请定义proxy.conf.js中的配置。

const PROXY_CONFIG = [
    {
        context: [
            "/my",
            "/many",
            "/endpoints",
            "/i",
            "/need",
            "/to",
            "/proxy"
        ],
        target: "http://localhost:3000",
        secure: false
    }
]

module.exports = PROXY_CONFIG;

Bypass the Proxy

If you need to optionally bypass the proxy, or dynamically change the request before it's sent, define the configuration in proxy.conf.js e.g.

如果您需要选择绕过代理,或在发送请求之前动态更改请求,请在proxy.conf.js中定义配置。

const PROXY_CONFIG = {
    "/api/proxy": {
        "target": "http://localhost:3000",
        "secure": false,
        "bypass": function (req, res, proxyOptions) {
            if (req.headers.accept.indexOf("html") !== -1) {
                console.log("Skipping proxy for browser request.");
                return "/index.html";
            }
            req.headers["X-Custom-Header"] = "yes";
        }
    }
}

module.exports = PROXY_CONFIG;