angular-cli 서버-API 요청을 다른 서버로 프록시하는 방법은 무엇입니까?
angular-cli
ng serve
로컬 개발 서버를 사용하면 내 프로젝트 디렉토리의 모든 정적 파일을 제공합니다.
내 AJAX 호출을 다른 서버로 프록시하려면 어떻게해야합니까?
2017 업데이트
이제 더 나은 문서를 사용할 수 있으며 JSON 및 JavaScript 기반 구성을 모두 사용할 수 있습니다. angular-cli 문서 프록시
https 프록시 구성 샘플
{
"/angular": {
"target": {
"host": "github.com",
"protocol": "https:",
"port": 443
},
"secure": false,
"changeOrigin": true,
"logLevel": "info"
}
}
Angular 2.0 릴리스에 대해 알고있는 한 .ember-cli 파일을 사용하여 프록시를 설정하는 것은 권장되지 않습니다. 공식적인 방법은 다음과 같습니다
아래를 볼
"start"
수package.json
있도록 수정"start": "ng serve --proxy-config proxy.conf.json",
proxy.conf.json
프로젝트의 루트에 새 파일을 만들고 그 안에 아래와 같이 프록시를 정의합니다.{ "/api": { "target": "http://api.yourdomai.com", "secure": false } }
중요한 것은
npm start
대신 사용하는 것입니다.ng serve
여기에서 더 많은 것을 읽으십시오 : Proxy Setup Angular 2 cli
이것은 나를 위해 일하는 것에 가깝습니다. 또한 다음을 추가해야했습니다.
"changeOrigin": true,
"pathRewrite": {"^/proxy" : ""}
전체는 proxy.conf.json
아래와 같습니다.
{
"/proxy/*": {
"target": "https://url.com",
"secure": false,
"changeOrigin": true,
"logLevel": "debug",
"pathRewrite": {
"^/proxy": ""
}
}
}
이 예 에서 알아야 할 모든 것을 설명하겠습니다 .
{
"/folder/sub-folder/*": {
"target": "http://localhost:1100",
"secure": false,
"pathRewrite": {
"^/folder/sub-folder/": "/new-folder/"
},
"changeOrigin": true,
"logLevel": "debug"
}
}
/ folder / sub-folder / * 경로는 다음과 같이 말합니다. angular 2 응용 프로그램 내에서이 경로를 볼 때 (경로는 어디에나 저장할 수 있음)이 경로로 무언가를하고 싶습니다. * 문자는 하위 폴더 뒤에 오는 모든 항목이 포함됨을 나타냅니다. 예를 들어 / folder / sub-folder / 안에 여러 글꼴이있는 경우 *는 모든 글꼴 을 선택합니다.
"target" : " http : // localhost : 1100 "위의 경로에 대해 target url을 호스트 / 소스로 만듭니다 . 따라서 백그라운드에서는 http : // localhost : 1100 / folder / sub-folder /가 있습니다.
"pathRewrite ": { "^ / folder / sub-folder /": "/ new-folder /"}, 이제 응용 프로그램을 로컬에서 테스트한다고 가정 해 보겠습니다. http : // localhost : 1100 / folder / sub- folder / 에 잘못된 경로가 포함되어있을 수 있습니다 : / folder / sub-folder /. 이 경로를 http : // localhost : 1100 / new-folder / 올바른 경로로 변경하려고 하므로 pathRewrite가 매우 유용합니다. 응용 프로그램의 경로 (왼쪽)를 제외하고 새로 작성된 경로 (오른쪽)를 포함합니다.
"secure" 속성은 http 또는 https 사용 여부를 나타냅니다. https가 대상 속성에 사용되는 경우 보안 속성을 true로 설정하고 그렇지 않으면 false로 설정하십시오.
"changeOrigin" : 호스트 대상이 현재 환경이 아닌 경우에만 옵션이 필요합니다 (예 : localhost). 호스트를 프록시의 대상이 될 www.something.com으로 변경하려면 changeOrigin 속성을 "true"로 설정합니다.
"logLevel" 속성은 개발자가 자신의 터미널에서 프록 싱을 출력 할 것인지 지정하므로 이미지에 표시된대로 "debug"값을 사용합니다.
일반적으로 프록시는 로컬에서 응용 프로그램을 개발하는 데 도움이됩니다. 프로덕션 목적으로 파일 경로를 설정하고 이러한 모든 파일이 프로젝트 내부에 로컬로있는 경우 앱에서 경로를 동적으로 변경하지 않고 프록시를 사용하여 액세스 할 수 있습니다.
작동하면 cmd / 터미널에 다음과 같은 내용이 표시됩니다.
편집 : 현재 ANGULAR-CLI에서 더 이상 작동하지 않습니다.
최신 솔루션은 @imal hasaranga perera의 답변을 참조하십시오.
의 서버 angular-cli
는 ember-cli
프로젝트 에서 가져 옵니다 . 서버를 구성하려면 .ember-cli
프로젝트 루트에 파일을 만듭니다 . 거기에 JSON 구성을 추가하십시오.
{
"proxy": "https://api.example.com"
}
서버를 다시 시작하면 모든 요청이 프록시됩니다.
예를 들어, 나는 내 코드에서 상대 요청을 만들고있어 /v1/foo/123
에서 포착되고있다, https://api.example.com/v1/foo/123
.
서버를 시작할 때 플래그를 사용할 수도 있습니다. ng serve --proxy https://api.example.com
angular-cli 버전의 현재 버전 : 1.0.0-beta.0
Angular-CLI에 대한 프록시 문서는 여기에서 찾을 수 있습니다.
https://github.com/angular/angular-cli/blob/master/docs/documentation/stories/proxy.md
루트 폴더에 proxy.conf.json이라는 파일을 설정 한 후 시작할 때 프록시 구성을 포함하도록 package.json을 편집합니다. "start": "ng serve --proxy-config proxy.conf.json"을 스크립트에 추가 한 후 package.json의 플래그 설정을 무시하므로 ng serve가 아닌 npm start를 실행합니다.
angular-cli의 현재 버전 : 1.1.0
더 많은 유연성이 필요할 때 프록시를 사용하는 또 다른 방법은 다음과 같습니다.
'라우터'옵션과 일부 자바 스크립트 코드를 사용하여 대상 URL을 동적으로 다시 작성할 수 있습니다. 이를 위해 'start'스크립트 매개 변수 목록에서 --proxy-conf 매개 변수로 json 파일 대신 javascript 파일을 지정해야합니다.
"start": "ng serve --proxy-config proxy.conf.js --base-href /"
위에 표시된대로 --base-href 매개 변수도 /로 설정해야합니다. 그렇지 않으면 <base href = "...">를 index.html의 경로로 설정해야합니다. 이 설정은이를 재정의하고 http 요청의 URL이 올바르게 구성되었는지 확인해야합니다.
그런 다음 proxy.conf.js에 다음 또는 유사한 콘텐츠가 필요합니다 (json이 아닙니다!).
const PROXY_CONFIG = {
"/api/*": {
target: https://www.mydefaulturl.com,
router: function (req) {
var target = 'https://www.myrewrittenurl.com'; // or some custom code
return target;
},
changeOrigin: true,
secure: false
}
};
module.exports = PROXY_CONFIG;
Note that the router option can be used in two ways. One is when you assign an object containing key value pairs where the key is the requested host/path to match and the value is the rewritten target URL. The other way is when you assign a function with some custom code, which is what I'm demonstrating in my examples here. In the latter case I found that the target option still needs to be set to something in order for the router option to work. If you assign a custom function to the router option then the target option is not used so it could be just set to true. Otherwise, it needs to be the default target URL.
Webpack uses http-proxy-middleware so you'll find useful documentation there: https://github.com/chimurai/http-proxy-middleware/blob/master/README.md#http-proxy-middleware-options
The following example will get the developer name from a cookie to determine the target URL using a custom function as router:
const PROXY_CONFIG = {
"/api/*": {
target: true,
router: function (req) {
var devName = '';
var rc = req.headers.cookie;
rc && rc.split(';').forEach(function( cookie ) {
var parts = cookie.split('=');
if(parts.shift().trim() == 'dev') {
devName = decodeURI(parts.join('='));
}
});
var target = 'https://www.'+ (devName ? devName + '.' : '' ) +'mycompany.com';
//console.log(target);
return target;
},
changeOrigin: true,
secure: false
}
};
module.exports = PROXY_CONFIG;
(The cookie is set for localhost and path '/' and with a long expiry using a browser plugin. If the cookie doesn't exist, the URL will point to the live site.)
Here is another working example (@angular/cli 1.0.4):
proxy.conf.json :
{
"/api/*" : {
"target": "http://localhost:8181",
"secure": false,
"logLevel": "debug"
},
"/login.html" : {
"target": "http://localhost:8181/login.html",
"secure": false,
"logLevel": "debug"
}
}
run with :
ng serve --proxy-config proxy.conf.json
It's important to note that the proxy path will be appended to whatever you configured as your target. So a configuration like this:
{
"/api": {
"target": "http://myhost.com/api,
...
}
}
and a request like http://localhost:4200/api
will result in a call to http://myhost.com/api/api
. I think the intent here is to not have two different paths between development and production environment. All you need to do is using /api
as your base URL.
따라서 올바른 방법은 api 경로 앞에 오는 부분,이 경우 호스트 주소 만 사용하는 것입니다.
{
"/api": {
"target": "http://myhost.com",
...
}
}
'IT박스' 카테고리의 다른 글
자바 스크립트 캔버스로 이미지 크기 조정 (부드럽게) (0) | 2020.10.29 |
---|---|
지정된 행 수에 따라 CSV 파일을 분할하는 방법은 무엇입니까? (0) | 2020.10.28 |
iPhone에서 빈 영역을 터치하면 키보드를 숨기는 방법 (0) | 2020.10.28 |
Java에서 문자열 부분 제거 (0) | 2020.10.28 |
NSURLConnection에 대한 Xcode 4 경고 "표현 결과가 사용되지 않음" (0) | 2020.10.28 |