angular-CLI代理后端

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
使用 webpacks 開發(fā)服務(wù)器中的代理支持, 我們可以劫持某些 url 并將它們發(fā)送到后端服務(wù)器捺典。我們這樣做是通過傳遞一個(gè)文件給 --proxy-config 選項(xiàng)。

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.
假設(shè)我們有一個(gè)服務(wù)器運(yùn)行在 http://localhost:3000/api 我們希望所有調(diào)用 http://localhost:4200/api 到該服務(wù)器上.

We create a file next to our project's package.json called proxy.conf.json with the content
我們在項(xiàng)目包旁邊創(chuàng)建一個(gè)文件 package.json 命名為 proxy.conf.json 和如下的內(nèi)容种远。

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

You can read more about what options are available here.
您可以閱讀更多關(guān)于此處.可用選項(xiàng)的信息屏歹。

We can then add the proxyConfig option to the serve target:
然后, 我們可以將 proxyConfig 選項(xiàng)添加到服務(wù)目標(biāo):

"architect": {
  "serve": {
    "builder": "@angular-devkit/build-angular:dev-server",
    "options": {
      "browserTarget": "your-application-name:build",
      "proxyConfig": "src/proxy.conf.json"
    },

Now in order to run our dev server with our proxy config we can call ng serve.

現(xiàn)在, 為了運(yùn)行我們的開發(fā)服務(wù)器與我們的代理配置, 我們可以調(diào)用
ng serve.

After each edit to the proxy.conf.json file remember to relaunch the ng serve process to make your changes effective.
每次編輯到 proxy.conf.json 文件后, 記住重新啟動(dòng) ng serve 進(jìn)程, 使您的更改生效

Rewriting the URL path

重寫url路徑

One option that comes up a lot is rewriting the URL path for the proxy. This is supported by the pathRewrite option.
一個(gè)很重要的選項(xiàng)是重寫代理的 URL 路徑苏章。這由 pathRewrite 選項(xiàng)支持

Say we have a server running on http://localhost:3000 and we want all calls to http://localhost:4200/api to go to that server.
假設(shè)我們有一個(gè)服務(wù)器運(yùn)行在 http://localhost:3000, 我們希望所有調(diào)用 http://localhost:4200/api 到該服務(wù)器上轰传。

in our proxy.conf.json file, we add the following content
在我們的 proxy.conf.json 文件, 我們添加如下內(nèi)容

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

If you need to access a backend that is not on localhost, you will need to add the changeOrigin option as follows:
如果您需要訪問不在本地主機(jī)上的后端,則需要添加 changeOrigin 選項(xiàng)要门,如下所示:

{
  "/api": {
    "target": "http://npmjs.org",
    "secure": false,
    "pathRewrite": {
      "^/api": ""
    },
    "changeOrigin": true
  }
}

To help debug whether or not your proxy is working properly, you can also add the logLevel option as follows:
為了幫助調(diào)試代理是否正常工作榜晦,您還可以添加 logLevel 選項(xiàng)冠蒋,如下所示:

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

Possible options for logLevel include debug, info, warn, error, and silent (default is info)
logLevel 的可能選項(xiàng)包括 debug, info, warn, error, 和 silent (默認(rèn)是info)

Multiple entries

多入口

If you need to proxy multiple entries to the same target define the configuration in proxy.conf.js instead of proxy.conf.json e.g.
如果需要將多個(gè)條目代理到同一目標(biāo),請?jiān)?proxy.conf.js 中定義配置乾胶,而不是proxy.conf.json 中的配置抖剿,例如

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

module.exports = PROXY_CONFIG;

Make sure to point to the right file (.js instead of .json):
確保指向正確的文件 (.js 而不是 .json):

"architect": {
  "serve": {
    "builder": "@angular-devkit/build-angular:dev-server",
    "options": {
      "browserTarget": "your-application-name:build",
      "proxyConfig": "src/proxy.conf.js"
    },

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.
如果需要繞過代理,或者在請求發(fā)送前動(dòng)態(tài)更改請求识窿,請?jiān)趐roxy.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;

Using corporate proxy

使用企業(yè)代理

If you work behind a corporate proxy, the regular configuration will not work if you try to proxy
calls to any URL outside your local network.
如果您在公司代理的后面工作喻频,如果您嘗試將呼叫代理到本地網(wǎng)絡(luò)之外的任何URL缩宜,則常規(guī)配置將不起作用

In this case, you can configure the backend proxy to redirect calls through your corporate
proxy using an agent:
在這種情況下,您可以配置后端代理以使用代理通過公司代理重定向呼叫

npm install --save-dev https-proxy-agent

Then instead of using a proxy.conf.json file, we create a file called proxy.conf.js with
the following content:
然后甥温,我們不使用 proxy.conf.json 文件锻煌,而是使用以下內(nèi)容創(chuàng)建一個(gè)名為 proxy.conf.js 的文件:

var HttpsProxyAgent = require('https-proxy-agent');
var proxyConfig = [{
  context: '/api',
  target: 'http://your-remote-server.com:3000',
  secure: false
}];

function setupForCorporateProxy(proxyConfig) {
  var proxyServer = process.env.http_proxy || process.env.HTTP_PROXY;
  if (proxyServer) {
    var agent = new HttpsProxyAgent(proxyServer);
    console.log('Using corporate proxy server: ' + proxyServer);
    proxyConfig.forEach(function(entry) {
      entry.agent = agent;
    });
  }
  return proxyConfig;
}

module.exports = setupForCorporateProxy(proxyConfig);

This way if you have a http_proxy or HTTP_PROXY environment variable defined, an agent will automatically be added to pass calls through your corporate proxy when running npm start.
這樣,如果您定義了 http_proxyHTTP_PROXY 環(huán)境變量姻蚓,則在運(yùn)行 npm start 時(shí)宋梧,會(huì)自動(dòng)添加代理以通過公司代理傳遞調(diào)用。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末狰挡,一起剝皮案震驚了整個(gè)濱河市捂龄,隨后出現(xiàn)的幾起案子释涛,更是在濱河造成了極大的恐慌,老刑警劉巖倦沧,帶你破解...
    沈念sama閱讀 217,406評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件唇撬,死亡現(xiàn)場離奇詭異,居然都是意外死亡展融,警方通過查閱死者的電腦和手機(jī)局荚,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,732評論 3 393
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來愈污,“玉大人,你說我怎么就攤上這事轮傍≡荼ⅲ” “怎么了?”我有些...
    開封第一講書人閱讀 163,711評論 0 353
  • 文/不壞的土叔 我叫張陵创夜,是天一觀的道長杭跪。 經(jīng)常有香客問我,道長驰吓,這世上最難降的妖魔是什么涧尿? 我笑而不...
    開封第一講書人閱讀 58,380評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮檬贰,結(jié)果婚禮上姑廉,老公的妹妹穿的比我還像新娘。我一直安慰自己翁涤,他們只是感情好桥言,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,432評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著葵礼,像睡著了一般号阿。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上鸳粉,一...
    開封第一講書人閱讀 51,301評論 1 301
  • 那天扔涧,我揣著相機(jī)與錄音,去河邊找鬼届谈。 笑死枯夜,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的艰山。 我是一名探鬼主播卤档,決...
    沈念sama閱讀 40,145評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼程剥!你這毒婦竟也來了劝枣?” 一聲冷哼從身側(cè)響起汤踏,我...
    開封第一講書人閱讀 39,008評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎舔腾,沒想到半個(gè)月后溪胶,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,443評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡稳诚,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,649評論 3 334
  • 正文 我和宋清朗相戀三年哗脖,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片扳还。...
    茶點(diǎn)故事閱讀 39,795評論 1 347
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡才避,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出氨距,到底是詐尸還是另有隱情桑逝,我是刑警寧澤,帶...
    沈念sama閱讀 35,501評論 5 345
  • 正文 年R本政府宣布俏让,位于F島的核電站楞遏,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏首昔。R本人自食惡果不足惜寡喝,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,119評論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望勒奇。 院中可真熱鬧预鬓,春花似錦、人聲如沸赊颠。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,731評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽巨税。三九已至蟋定,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間草添,已是汗流浹背驶兜。 一陣腳步聲響...
    開封第一講書人閱讀 32,865評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留远寸,地道東北人抄淑。 一個(gè)月前我還...
    沈念sama閱讀 47,899評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像驰后,于是被迫代替她去往敵國和親肆资。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,724評論 2 354

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理灶芝,服務(wù)發(fā)現(xiàn)郑原,斷路器唉韭,智...
    卡卡羅2017閱讀 134,654評論 18 139
  • This project was bootstrapped with Create React App. Belo...
    unspecx閱讀 5,163評論 0 2
  • 說在前面:今天想分享一篇古典老師的文章,文章中他分析了常人對于工作和工資的三個(gè)誤區(qū)犯犁,我看了好幾遍属愤,受益匪淺。關(guān)于工...
    王二寶閱讀 326評論 0 0
  • 1.越王勾踐劍 越王勾踐劍酸役,堪稱“天下第一劍"住诸!非常的短。它通高55.6厘米涣澡,寬4.6厘米柄長為8.4厘米贱呐,重87...
    鄧小可閱讀 816評論 0 0
  • 1月7日日精進(jìn):敬畏—進(jìn)入—體驗(yàn)—交給—持續(xù) 1,缺啥補(bǔ)啥,怕啥練啥入桂; 2,一切為我所用奄薇,所用為團(tuán)隊(duì)家; 3事格,我...
    王全峰閱讀 165評論 0 0