Error occurred while trying to proxy request angular

OS? Windows 10 Versions. angular-cli: 1.0.0-beta.26 node: 7.5.0 os: win32 x64 Repro steps. git clone https://github.com/doggy8088/angular-cli-https-proxy-error.git cd angular-cli-https-proxy-error ...

@doggy8088

OS?

Windows 10

Versions.

angular-cli: 1.0.0-beta.26
node: 7.5.0
os: win32 x64

Repro steps.

  1. git clone https://github.com/doggy8088/angular-cli-https-proxy-error.git
  2. cd angular-cli-https-proxy-error
  3. npm install
  4. npm start
  5. Open ‘http://localhost:4200/_/help’ ( this should proxy request to https://jsonbin.org/_/help )
  • The page output will be Erroroccured while trying to proxy to: localhost:4200/_/help.
  • The console output will be [HPM] Error occurred while trying to proxy request /_/help from localhost:4200 to https://jsonbin.org (EPROTO) (https://nodejs.org/api/errors.html#errors_common_system_errors).

The log given by the failure.

[HPM] Error occurred while trying to proxy request /_/help from localhost:4200 to https://jsonbin.org (EPROTO) (https://nodejs.org/api/errors.html#errors_common_system_errors)

Some useful details

I tested some https webiste without any proxy request problem. Don’t know why I just can’t proxy my https request to https://jsonbin.org website. I need to proxy my API request to that domain.

I want to log more detail about the error. I was trying to edit the node_moduleshttp-proxy-middlewarelibindex.js file for Line 145 shown as below to show the err message.

logger.error('[HPM] Error occurred while trying to proxy request %s from %s to %s (%s) (%s)', req.url, hostname, target, err.code, err);

Here is the error output:

[HPM] Error occurred while trying to proxy request /_/help from localhost:4200 to https://jsonbin.org (EPROTO) (Error: write EPROTO 101057795:error:14077438:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert internal error:opensslssls23_clnt.c:769:
)

I do can browse all these urls by browser or can send request directly from Postman. It just can’t send requests to some https urls from angular-cli proxy feature.

@remy

I’m pretty certain that this is because the target, jsonbin.org is under https and the proxy isn’t being trusted. Without really knowing what I’m talking about, the SSL cert from jsonbin.org isn’t trusted in the response/proxy in Angular?

I’ve certainly ruled this out by running a local version of jsonbin over http, and the proxy worked fine.

I’m not sure how you’d work around it without having to manually intervene and proxy the request with something like the request module.

I don’t think this is a bug though, on either angular or jsonbin’s side.

@doggy8088



Copy link


Contributor

Author

@remy I tried to use http-proxy-middleware standalone. There is no problem to build proxy tunnel to jsonbin.org. See below:

var express = require('express');
var proxy = require('http-proxy-middleware');
 
var app = express();
 
app.use('/api', proxy({target: 'https://jsonbin.org', changeOrigin: true}));
app.listen(3000);

It maybe some problem from webpack or something. I’m not sure.

@Meligy

This might be a stupid check, but do you have a "secure": true property in your proxy definition as per the README sample?

@doggy8088



Copy link


Contributor

Author

@doggy8088



Copy link


Contributor

Author

@remy I finally figured out how this issue happen.

Your web server configured SNI SSL which means you can install multiple SSL certified on one IP address. So your website can’t accept any domain that are registered on your web server. The webpack dev server need to configure Proxying local virtual hosts in order to keep the hostname on the proxy request to the target server. That’s the key point on this issue I met yesterday.

So here is the right proxy.config.json settings in order to setup Angular-CLI proxy to your jsonbin.org site.

{
  "/**": {
    "target": {
        "host": "jsonbin.org",
        "protocol": "https:",
        "port": 443
      },
    "secure": false,
    "changeOrigin": true,
    "logLevel": "info"
  }
}

😺

chiachun0920, nheidloff, JackCiou751, kiwikern, Guatom, equiman, outsideMyBox, Lianathanoj, hasan-wajahat, sandhaka, and 30 more reacted with thumbs up emoji
nicejade, pulsejet, and Mds92 reacted with laugh emoji
Adam95, krlng, pacurtin, mscoobby, developer239, kodurianil, dionatanribeiro, josephjsf2, Mds92, and AnMa12 reacted with hooray emoji
kodurianil, Pieter-hogent, Mds92, and AnMa12 reacted with heart emoji

@grigorig

This doesn’t work for me. Using Angular CLI 6.0.8 and NodeJS 8.11.3, I can’t get the proxy to send the servername, no matter what I set in the proxy configuration. Any ideas?

@smilemuffie

This proxy.config.json worked for me. Thanks!

@angular-automatic-lock-bot

This issue has been automatically locked due to inactivity.
Please file a new issue if you are encountering a similar or related problem.

Read more about our automatic conversation locking policy.

This action has been performed automatically by a bot.

Issue

I am following a tutorial (https://levelup.gitconnected.com/simple-application-with-angular-6-node-js-express-2873304fff0f) on creating an app with Angula CLI, Node.js and Express. I use a proxy to start the app, the file defining the proxy looks like this:

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

The command I use to start the app is this one:

ng serve —proxy-config proxy.conf.json

The tutorial said that:

All requests made to /api/... from within our application will be forwarded to http://localhost:3000/api/...

To be honest, I don’t really know how it is supposed to work, because when I launch the app, I still use the URL: http://localhost:4200/ .

But I didn’t have a problem until now. I just created a route with Express.js at the Endpoint /api/v1/generate_uid .

But the problem is when I go to http://localhost:4200/api/v1/generate_uid it shows this message:

Error occured while trying to proxy to: localhost:4200/api/v1/generate_uid .

The following is the message I get in the console:

[HPM] Error occurred while trying to proxy request /api/v1/generate_uid from localhost:4200 to http://localhost:3000 (ECONNREFUSED) (https://nodejs.org/api/errors.html#errors_common_system_errors)

And when I go to http://localhost:3000 it always says that the connection has failed.

For further references, Here are the app.js of my express API and generate_uid.js which defines the route:

app.js

var express = require('express');
var uid = require('uid-safe');

var router = express.Router();

router.get('/', function(req, res, next) {
    var strUid = uid.sync(18);
    res.json({guid: strUid});
});

module.exports = router;

generate_uid.js

var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var users = require('./routes/users');
var generate_uid = require('./routes/generate_uid');

var app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser())

app.use('/api/v1/users', users);
app.use('/api/v1/generate_uid', generate_uid);

module.exports = app;

So I really don’t know what the solution is. Thanks in advance for your answers !!

Solution

As said in the comments, it looks like the app doesn’t have the .listen() function, which is very important to bind to the port.

app.listen(3000, () => {
  console.log("Server started in port 3000!");
});

Answered By — Praveen Kumar Purushothaman

Содержание

  1. Angular-CLI прокси не работает внутри докера
  2. 4 ответа
  3. Вы искали: an error occurred, please try again later (Английский — Русский)
  4. Переводы пользователей
  5. Английский
  6. Русский
  7. Информация
  8. Английский
  9. Русский
  10. Английский
  11. Русский
  12. Английский
  13. Русский
  14. Английский
  15. Русский
  16. Английский
  17. Русский
  18. Английский
  19. Русский
  20. Английский
  21. Русский
  22. Английский
  23. Русский
  24. Английский
  25. Русский
  26. Английский
  27. Русский
  28. Английский
  29. Русский
  30. Английский
  31. Русский
  32. Английский
  33. Русский
  34. Английский
  35. Русский
  36. Английский
  37. Русский
  38. Английский
  39. Русский
  40. Английский
  41. Русский
  42. Английский
  43. Русский
  44. Английский
  45. Русский
  46. Английский
  47. Русский
  48. Получите качественный перевод благодаря усилиям 4,401,923,520 пользователей
  49. Докер не принимает прокси-сервер api
  50. ОБНОВЛЕНИЕ: подход network_mode
  51. Русские Блоги
  52. [antd] Ошибка конфигурации локального агента отладки UNABLE_TO_VERIFY_LEAF_SIGNATURE
  53. Интеллектуальная рекомендация
  54. IView CDN Загрузка значка шрифта нормальная, а значок шрифта не может быть загружен при локальной загрузке JS и CSS
  55. Критическое: ошибка настройки прослушивателя приложения класса org.springframework.web.context.ContextLoaderLis
  56. 1086 Не скажу (15 баллов)
  57. Pandas применяют параллельный процесс приложения, многоядерная скорость очистки данных
  58. PureMVC Learning (Tucao) Примечания
  59. Вы искали: an error occurred, please try again later (Английский — Русский)
  60. Переводы пользователей
  61. Английский
  62. Русский
  63. Информация
  64. Английский
  65. Русский
  66. Английский
  67. Русский
  68. Английский
  69. Русский
  70. Английский
  71. Русский
  72. Английский
  73. Русский
  74. Английский
  75. Русский
  76. Английский
  77. Русский
  78. Английский
  79. Русский
  80. Английский
  81. Русский
  82. Английский
  83. Русский
  84. Английский
  85. Русский
  86. Английский
  87. Русский
  88. Английский
  89. Русский
  90. Английский
  91. Русский
  92. Английский
  93. Русский
  94. Английский
  95. Русский
  96. Английский
  97. Русский
  98. Английский
  99. Русский
  100. Английский
  101. Русский
  102. Английский
  103. Русский
  104. Получите качественный перевод благодаря усилиям 4,401,923,520 пользователей

Angular-CLI прокси не работает внутри докера

У меня есть файл docker-compose со всем, что мне нужно для моего проекта.

Этот docker-compose имеет сервер nginx, mysql, phpmyadmin и php. В довершение всего, я недавно добавил угловой контейнер. Все работает нормально, если я перехожу на localhost: 4200, я нахожусь в угловом приложении, и если я иду на localhost: 80, я на бэкэнде Laravel.

Теперь мне нужно сделать простой классический запрос к моему внутреннему API. Я настроил прокси-сервер для углового вида:

Это конфигурация, которую я скопировал, основываясь на этой теме. Но когда я пытаюсь сделать звонок, Chrome говорит, что http: // localhost: 4200 / api / test не существует (ошибка 404), что нормально. С другой стороны, угловой сервер говорит
HPM] Error occurred while trying to proxy request /test from localhost:4200 to http://localhost:80 (ECONNREFUSED) (https://nodejs.org/api/errors.html#errors_common_system_errors)

Я предполагаю, что это исходит от докера, но я не могу понять, как решить эту проблему.

А вот Dockerfiles для PHP и Angular:

4 ответа

Я исправил проблему, удалив Angular из докера и запустив его вручную с помощью простого npm start .

Чтобы решить эту проблему, я просто создал ссылку в сервисе frontend / client для моего сервиса api в файле docker compose:

После этого я обновил свой конфигурационный файл прокси в папке angular / client:

ПРИМЕЧАНИЕ : целевой URL-адрес совпадает с файлом компоновщика докера: api , и не забывайте о незащищенном порте, в моем случае это 5000.

Ваша проблема в том, что вы не копируете package.json и npm install ничего не делает, когда нет package.json

Измените свой угловой файл на ниже

Это установит ваши node_nodules в $NODE_PATH , который /usr/src/node_modules

Измените свой угловой сервис в compose, как показано ниже

Дополнительная запись для package.json не требуется. Теперь, несмотря на то, что вы перезаписали бы /usr/src/app/node_modules из монтирования локальной папки, мы изменили модули узлов, чтобы их можно было найти в /usr/src/node_modules

Я смог заставить это работать после большой отладки.

Решение @MSLacerda работает, но я хотел добавить ответ с докерными сетями, поскольку ссылки на докеры устарели.

Источник

Вы искали: an error occurred, please try again later (Английский — Русский)

Переводы пользователей

Добавлены профессиональными переводчиками и компаниями и на основе веб-страниц и открытых баз переводов.

Английский

Русский

Информация

Английский

an error has occurred, please try again later

Русский

произошла ошибка, пожалуйста попробуйте позже

Последнее обновление: 2020-03-08
Частота использования: 1
Качество:
Источник: Анонимно

Английский

some error occurred please try again

Русский

произошла ошибка, попробуйте еще раз

Последнее обновление: 2021-01-08
Частота использования: 1
Качество:
Источник: Анонимно

Английский

an error occured. please try again later.

Русский

обнаружена ошибка. Пожалуйста, попробуйте позже.

Последнее обновление: 2018-02-21
Частота использования: 1
Качество:
Источник: Анонимно

Английский

an error occurred trying to send your message. please try again later.

Русский

Произошла ошибка при попытке отправить сообщение. Пожалуйста, повторите попытку позже.

Последнее обновление: 2013-02-17
Частота использования: 1
Качество:
Источник: Анонимно

Английский

please try again later

Русский

Пожалуйста, повторите попытку позже

Последнее обновление: 2018-02-21
Частота использования: 2
Качество:
Источник: Анонимно

Английский

please try again later.

Русский

please try again later.

Последнее обновление: 2018-02-21
Частота использования: 1
Качество:
Источник: Анонимно

Английский

please try again later. )

Русский

Последнее обновление: 2018-02-21
Частота использования: 2
Качество:
Источник: Анонимно

Английский

an error occurred while trying to download the dictionary. please try again later.

Русский

Во время загрузки словаря возникла ошибка. Повторите попытку позднее.

Последнее обновление: 2015-03-16
Частота использования: 1
Качество:
Источник: Анонимно

Английский

failed please try again later

Русский

Неудача, повторите попытку позже

Последнее обновление: 2022-11-10
Частота использования: 1
Качество:
Источник: Анонимно

Английский

an error occurred while sending the data. please try later again.

Русский

an error occurred while sending the data. please try later again.

Последнее обновление: 2018-02-21
Частота использования: 1
Качество:
Источник: Анонимно

Английский

an internal error occurred. please retry the request again.

Русский

Произошла внутренняя ошибка. Повторите запрос ещё раз.

Последнее обновление: 2011-10-23
Частота использования: 1
Качество:
Источник: Анонимно

Английский

download failed, please try again the later

Русский

le téléchargement a échoué, veuillez réessayer plus tard

Последнее обновление: 2022-04-04
Частота использования: 5
Качество:
Источник: Анонимно

Английский

an error occurred.

Русский

Последнее обновление: 2018-02-21
Частота использования: 1
Качество:
Источник: Анонимно

Английский

please try again!

Русский

Последнее обновление: 2018-02-21
Частота использования: 1
Качество:
Источник: Анонимно

Английский

the download has failed, please try again later.

Русский

Не удалось загрузить. Пожалуйста, повторите попытку позже.

Последнее обновление: 2016-03-15
Частота использования: 2
Качество:
Источник: Анонимно

Английский

error while sending message. please try again

Русский

При отправке сообщения возникла ошибка. Пожалуйста, попробуйте еще раз

Последнее обновление: 2018-02-21
Частота использования: 1
Качество:
Источник: Анонимно

Английский

the installation was unsuccessful. please try again later.

Русский

Не удалось установить. Пожалуйста, повторите попытку позже.

Последнее обновление: 2016-03-15
Частота использования: 2
Качество:
Источник: Анонимно

Английский

i may try again later

Русский

Я, может, потом ещё раз попробую

Последнее обновление: 2020-11-06
Частота использования: 1
Качество:
Источник: Анонимно

Английский

let’s try again later

Русский

Давай попробуем потом

Последнее обновление: 2020-11-06
Частота использования: 1
Качество:
Источник: Анонимно

Английский

download failed, please try again

Русский

Последнее обновление: 2022-07-16
Частота использования: 1
Качество:
Источник: Анонимно

Получите качественный перевод благодаря усилиям
4,401,923,520 пользователей

Сейчас пользователи ищут:

MyMemory — крупнейшая в мире память переводов. Она была создана на основе систем памяти переводов Европейского Союза, Организации Объединенных Наций и ведущих специализированных многоязычных сайтов из разных отраслей.

Мы относимся к Translated, так что, если вам нужны услуги профессионального перевода, посетите наш основной сайт.

Источник

Докер не принимает прокси-сервер api

Я получаю следующую ошибку при выполнении docker-compose up. Приложение запущено, но не может делать никаких запросов api post / get. Экспресс-сервер использует порт 5000.

Несмотря на то, что прокси-сервер реакции настроен, ошибка сохраняется.

setupProxy.js

Dockerfile

docker-compose.yml

package.json

Я думаю, что вам нужно изменить localhost: 5000 на имя вашей службы в docker-compose.yml . В этом случае вам необходимо настроить любой сервер, который у вас запущен на localhost: 5000 в файле набора. Помните, что ваши контейнеры работают в сети Docker, поэтому они не могут получить доступ к вашему локальному хосту на хост-машине.

В этом примере вы можете видеть, что мне нужно было установить переменную среды PMA_HOST для службы db вместо «обычного хоста». В конфигурации базы данных в моем исходном коде я также настроил хост для той же службы db, и все работает просто отлично.

Это необходимо, потому что каждый раз, когда вы запускаете новый контейнер, он будет получать другой IP-адрес в новой сети Docker. В этом случае нам всегда нужно будет проверять этот новый IP-адрес и устанавливать его в нашем коде. Docker решает эту проблему, позволяя нам привязать новый хост к простому и неизменяемому имени, которое в compose является именем службы.

ОБНОВЛЕНИЕ: подход network_mode

Если у вас уже есть служба, запущенная на вашем локальном хосте (например, сервер API), и вы используете докер для новой службы, которая будет взаимодействовать с этим API (например, пользовательский интерфейс веб-клиента), но по какой-то причине вы можете ‘ t или не хотите настраивать API в файле docker-compose.yml , вы можете изменить network_mode и environment HOST .

В этом подходе вам нужно будет сопоставить порт контейнера с неиспользуемым портом на хосте .

Итак, допустим, у вас работает API, localhost:80 и вы запускаете сервер узла на докере на порту 3000. Если у вас ничего не работает localhost:3000 , вы можете сделать следующее:

Источник

Русские Блоги

[antd] Ошибка конфигурации локального агента отладки UNABLE_TO_VERIFY_LEAF_SIGNATURE

Конфигурация локального агента отладки:

Решение: освободить сертификат от проверки

Интеллектуальная рекомендация

IView CDN Загрузка значка шрифта нормальная, а значок шрифта не может быть загружен при локальной загрузке JS и CSS

Используйте iview, чтобы сделать небольшой инструмент. Чтобы не затронуть другие платформы, загрузите JS и CSS CDN на локальные ссылки. В результате значок шрифта не может быть загружен. Просмо.

Критическое: ошибка настройки прослушивателя приложения класса org.springframework.web.context.ContextLoaderLis

1 Обзор Серверная программа, которая обычно запускалась раньше, открылась сегодня, и неожиданно появилась эта ошибка. Интуитивно понятно, что не хватает связанных с Spring пакетов, но после удаления п.

1086 Не скажу (15 баллов)

При выполнении домашнего задания друг, сидящий рядом с ним, спросил вас: «Сколько будет пять умножить на семь?» Вы должны вежливо улыбнуться и сказать ему: «Пятьдесят три». Это.

Pandas применяют параллельный процесс приложения, многоядерная скорость очистки данных

В конкурсе Algorith Algorith Algorith Algorith Algorith 2019 года используется многофункциональная уборка номера ускорения. Будет использовать панды. Но сама панда, кажется, не имеет механизма для мно.

PureMVC Learning (Tucao) Примечания

Справочная статья:Введение подробного PrueMVC Использованная литература:Дело UnityPureMvc Основная цель этой статьи состоит в том, чтобы организовать соответствующие ресурсы о PureMVC. Что касается Pu.

Источник

Вы искали: an error occurred, please try again later (Английский — Русский)

Переводы пользователей

Добавлены профессиональными переводчиками и компаниями и на основе веб-страниц и открытых баз переводов.

Английский

Русский

Информация

Английский

an error has occurred, please try again later

Русский

произошла ошибка, пожалуйста попробуйте позже

Последнее обновление: 2020-03-08
Частота использования: 1
Качество:
Источник: Анонимно

Английский

some error occurred please try again

Русский

произошла ошибка, попробуйте еще раз

Последнее обновление: 2021-01-08
Частота использования: 1
Качество:
Источник: Анонимно

Английский

an error occured. please try again later.

Русский

обнаружена ошибка. Пожалуйста, попробуйте позже.

Последнее обновление: 2018-02-21
Частота использования: 1
Качество:
Источник: Анонимно

Английский

an error occurred trying to send your message. please try again later.

Русский

Произошла ошибка при попытке отправить сообщение. Пожалуйста, повторите попытку позже.

Последнее обновление: 2013-02-17
Частота использования: 1
Качество:
Источник: Анонимно

Английский

please try again later

Русский

Пожалуйста, повторите попытку позже

Последнее обновление: 2018-02-21
Частота использования: 2
Качество:
Источник: Анонимно

Английский

please try again later.

Русский

please try again later.

Последнее обновление: 2018-02-21
Частота использования: 1
Качество:
Источник: Анонимно

Английский

please try again later. )

Русский

Последнее обновление: 2018-02-21
Частота использования: 2
Качество:
Источник: Анонимно

Английский

an error occurred while trying to download the dictionary. please try again later.

Русский

Во время загрузки словаря возникла ошибка. Повторите попытку позднее.

Последнее обновление: 2015-03-16
Частота использования: 1
Качество:
Источник: Анонимно

Английский

failed please try again later

Русский

Неудача, повторите попытку позже

Последнее обновление: 2022-11-10
Частота использования: 1
Качество:
Источник: Анонимно

Английский

an error occurred while sending the data. please try later again.

Русский

an error occurred while sending the data. please try later again.

Последнее обновление: 2018-02-21
Частота использования: 1
Качество:
Источник: Анонимно

Английский

an internal error occurred. please retry the request again.

Русский

Произошла внутренняя ошибка. Повторите запрос ещё раз.

Последнее обновление: 2011-10-23
Частота использования: 1
Качество:
Источник: Анонимно

Английский

download failed, please try again the later

Русский

le téléchargement a échoué, veuillez réessayer plus tard

Последнее обновление: 2022-04-04
Частота использования: 5
Качество:
Источник: Анонимно

Английский

an error occurred.

Русский

Последнее обновление: 2018-02-21
Частота использования: 1
Качество:
Источник: Анонимно

Английский

please try again!

Русский

Последнее обновление: 2018-02-21
Частота использования: 1
Качество:
Источник: Анонимно

Английский

the download has failed, please try again later.

Русский

Не удалось загрузить. Пожалуйста, повторите попытку позже.

Последнее обновление: 2016-03-15
Частота использования: 2
Качество:
Источник: Анонимно

Английский

error while sending message. please try again

Русский

При отправке сообщения возникла ошибка. Пожалуйста, попробуйте еще раз

Последнее обновление: 2018-02-21
Частота использования: 1
Качество:
Источник: Анонимно

Английский

the installation was unsuccessful. please try again later.

Русский

Не удалось установить. Пожалуйста, повторите попытку позже.

Последнее обновление: 2016-03-15
Частота использования: 2
Качество:
Источник: Анонимно

Английский

i may try again later

Русский

Я, может, потом ещё раз попробую

Последнее обновление: 2020-11-06
Частота использования: 1
Качество:
Источник: Анонимно

Английский

let’s try again later

Русский

Давай попробуем потом

Последнее обновление: 2020-11-06
Частота использования: 1
Качество:
Источник: Анонимно

Английский

download failed, please try again

Русский

Последнее обновление: 2022-07-16
Частота использования: 1
Качество:
Источник: Анонимно

Получите качественный перевод благодаря усилиям
4,401,923,520 пользователей

Сейчас пользователи ищут:

MyMemory — крупнейшая в мире память переводов. Она была создана на основе систем памяти переводов Европейского Союза, Организации Объединенных Наций и ведущих специализированных многоязычных сайтов из разных отраслей.

Мы относимся к Translated, так что, если вам нужны услуги профессионального перевода, посетите наш основной сайт.

Источник

Angular local transfer error: [HPM] Error occurred while trying to proxy request

Agent configuration

In front-end development, in order to solve the cross domain problem of browsers, devserver of webpack is generally used Proxy function to transfer the interface.

According to Angular’s documentation, the agent can be used in only four steps.

(1) Create proxy in src / directory Conf.json configuration file

(2) In proxy Transfer rules are written in the conf.json configuration file:

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

(3) In angular JSON configuration file, add the configuration of proxyConfig:

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

(3) Restart the project using ng serve

This is accessed in the Angular project http://localhost:4200/api Will automatically transfer to http://localhost:3000/api Interface.

A puzzling question

In this way, it can always run normally in the development environment. The computer was restarted last Friday and the error was reported on Monday.

The error message requested by the browser interface is as follows:

Error occured while trying to proxy to: localhost:4201/adminapi/login?AdminLogin

The errors reported in the terminal are as follows:

[HPM] POST /adminapi/login?AdminLogin -> http://localhost:8001/
[HPM] Error occurred while trying to proxy request /adminapi/login?AdminLogin 
 from localhost:4201 to http://localhost:8001/ 
  (ECONNREFUSED) 
  (https://nodejs.org/api/errors.html#errors_common_system_errors)

The HttpErrorResponse error printed in the HTTP interceptor is as follows:

HttpErrorResponse {
	headers: HttpHeaders, 
	status: 504, 
	statusText: "Gateway Timeout", 
	url: "http://localhost:4201/adminapi/login", 
	ok: false
}

Take a look at the configuration of the project

The front end uses Angular 11 and the back end uses PHP lumen 8 +.

For the convenience of PHP development, there is no built-in vastead + home web server.

$ php -S localhost:8001 -t ./public
[Mon Mar 22 17:31:34 2021] PHP 8.0.3 
  Development Server (http://localhost:8001) 
  started

The interface configuration is as follows:

// src/environments/environment.ts
export const environment = {
  production: false,
  // The address of the current ng startup, using proxy In the conf.json configuration, go to the address in the configuration
  apiHost: 'http://localhost:4201/api', 
  adminApi: 'http://localhost:4201/adminapi', 
};

Transfer file Src / proxy Conf.json is configured as follows:

{
  "/adminapi/*": {
    "target": "http://localhost:8001/",
    "secure": false,
    "changeOrigin": true,
    "logLevel": "debug"
  },
  "/api/*": {
    "target": "http://localhost:8001/",
    "secure": false,
    "changeOrigin": true,
    "logLevel": "debug"
  }
}

Online solutions

(1) Configuration file proxy Conf.json does not specify http or https: [excluded, not the problem]

# If http is not added, an error is reported
target: 'localhost:8081',  
# normal
target: 'http://localhost:8081', 

(2) Back end interface failed to start: [troubleshooting, not the problem]

You can see that the interface is normal. It is also normal to copy curl requests directly in the browser and execute requests in the terminal.

$ curl -XPOST localhost:8001
{"Status":401,"Msg":"Unauthorized.","Data":"","metadata":{}}%

(3) The proxy configuration rule is incorrect. [exclude, not the problem]

View the devserver. Of webpack Proxy configuration, and no abnormality is found.

Moreover, proxy The conf.json configuration file has not been changed, and it was normal before.

(4) Delete node_module to download the dependent package again. Reinstalled nodejs (v15.6). No.

(5) Some netizens pointed out that we should change localhost to ip access.

✔ Compiled successfully.

[HPM] POST /adminapi/login?AdminLogin -> http://127.0.0.1:8001/
[HPM] Error occurred while trying to proxy request /adminapi/login 
from localhost:4201 to http://127.0.0.1:8001/ 
 (ECONNREFUSED) 
 (https://nodejs.org/api/errors.html#errors_common_system_errors)

No. Continue to report errors.

In fact, there is a problem here. Subconsciously, I always think that localhost is equal to 127.0.0.1.

$ curl -XPOST 127.0.0.1:8001
curl: (7) Failed to connect to 127.0.0.1 port 8001: Connection refused

I don’t know why I can’t visit here. But ping to check localhost is also 127.0.0.1.

$ ping localhost
PING localhost (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.061 ms
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.255 ms
64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.181 ms
^C

At this time, I saw the article «a murder case caused by a localhost».

Devserver of webpack Proxy configuration actually uses the HTTP proxy middleware package.

On node_modules find this package and find a place where it runs out of error to check.

Find the logError function to achieve

// node_modules/http-proxy-middleware/lib/index.js

function logError(err, req, res) {
var hostname =
  (req.headers && req.headers.host) || (req.hostname || req.host)
var target = proxyOptions.target.host || proxyOptions.target
var errorMessage =
  '[HPM] Error occurred while trying to proxy request %s from %s to %s (%s) (%s)'
var errReference =
  'https://nodejs.org/api/errors.html#errors_common_system_errors'
 // < -------- print the log here 
 logger.error("==========> Print log: ")
 logger.error(err)

logger.error(
  errorMessage,
  req.url,
  hostname,
  target,
  err.code || err,
  errReference
)
}

You can see the output error log on the console.

[HPM] Error occurred while trying to proxy request /adminapi 
  from localhost:4201 to http://127.0.0.1:8001/ 
  (ECONNREFUSED) 
  (https://nodejs.org/api/errors.html#errors_common_system_errors)
[HPM] POST /adminapi?AdminGetTransactionList -> http://127.0.0.1:8001/
==========> Print log:
Error: connect ECONNREFUSED 127.0.0.1:8001
    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1138:16) {
  errno: -61,
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '127.0.0.1',
  port: 8001
}

You can see the original log, connect econnreused 127.0.0.1:8001. Sure enough, it’s because 127.0.0.1 can’t be accessed.

Solutions to current problems:

(1) Solve cross domain problems in the server background (interface configuration after online)

For example, use Homestead + Vagrant to configure the back-end development environment, and use add in Nginx_ Header configure access control allow origin policy.

(2) Use jsonp to solve cross domain problems. (this was commonly used in previous development with jQuery)

(3) The development continues to use PHP built-in web services, and the front end continues to use agents to solve cross domain problems by itself.

Restart the PHP background interface and use ip:

$ php -S localhost:8001 -t ./public

Change to:

$ php -S 127.0.0.1:8001 -t ./public

Reference link

http://blog.epoos.com/2018/05/21/proxy-error/
https://angular.io/guide/build
https://webpack.js.org/configuration/dev-server/#devserverproxy

Some https proxy urls failed #4322

Comments

Versions.

Repro steps.

  1. git clone https://github.com/doggy8088/angular-cli-https-proxy-error.git
  2. cd angular-cli-https-proxy-error
  3. npm install
  4. npm start
  5. Open ‘http://localhost:4200/_/help’ ( this should proxy request to https://jsonbin.org/_/help )
  • The page output will be Erroroccured while trying to proxy to: localhost:4200/_/help .
  • The console output will be [HPM] Error occurred while trying to proxy request /_/help from localhost:4200 to https://jsonbin.org (EPROTO) (https://nodejs.org/api/errors.html#errors_common_system_errors) .

The log given by the failure.

Some useful details

I tested some https webiste without any proxy request problem. Don’t know why I just can’t proxy my https request to https://jsonbin.org website. I need to proxy my API request to that domain.

I want to log more detail about the error. I was trying to edit the node_moduleshttp-proxy-middlewarelibindex.js file for Line 145 shown as below to show the err message.

logger.error(‘[HPM] Error occurred while trying to proxy request %s from %s to %s (%s) (%s)’, req.url, hostname, target, err.code, err);

Here is the error output:

[HPM] Error occurred while trying to proxy request /_/help from localhost:4200 to https://jsonbin.org (EPROTO) (Error: write EPROTO 101057795:error:14077438:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert internal error:opensslssls23_clnt.c:769:
)

I do can browse all these urls by browser or can send request directly from Postman. It just can’t send requests to some https urls from angular-cli proxy feature.

The text was updated successfully, but these errors were encountered:

Источник

Proxy not working when running ng serve #4676

Comments

Versions.

@angular/cli: 1.0.0-beta.31
node —version v6.9.1

Repro steps.

Need to run a proxy so I added —proxy-config proxy.conf.json in package.json
This works if I run npm start but then I cant access the site from my mobile on the same network.
If I run ng serve then I can use my mobile to test the site but the proxy stopps working.. ?

The text was updated successfully, but these errors were encountered:

It starts but I´m not able to navigate to 192.168.1.207:4200
(http://localhost:4200/ works on the laptop)

I was kind of hoping that adding something like «start»: «ng serve —proxy-config proxy.conf.json», to package.json would solve it for me but nope.. 🙁

Try using the —host flag with ng serve .

Like ng serve —proxy-conf proxy.conf.json —host 192.168.1.207
Or even ng serve —proxy-conf proxy.conf.json —host 0.0.0.0

It can also be stored in angular-cli.json under defaults :

Worked like a charm. thx! 🙂

Spoke to soon.
adding this to make it default didnt work :/

But it works if I run it in the terminal
ng serve —proxy-conf proxy.conf.json —host 0.0.0.0

It starts but proxy is not working..

I think to do 0.0.0.0 and to accept incoming connections from other laptops you need either a firewall rule or the process needs to run as admin. This is at least in Windows. Not sure if this is the specific problem or not.

We don’t support having the proxy-conf setting in the CLI json currently, only port/host/ssl/sslKey/sslCert. That is why it doesn’t work when you put it there.

I’ll accept it as a feature request if someone wants to take it on. Otherwise this is a consideration for 2.0 (having everything customizable in the config file).

@mackelito I added similar command line( ng serve —host 0.0.0.0 —port 4300 —proxy-config proxy.conf.json ) in package.json, and follow the Proxy to backend wiki page to create a proxy.conf.json in the same folder with package.json, but it still does not work.

I am using Windows 10, I am not sure if this is a system specific problem. When I used ng eject to export webpack.config.json and configure the proxy in the devServer section, it still get the same errors in cmd console.

I have added my detailed development environment in issue ##889 (comment)

fwiw, I could really use this. having a tough time putting authentication in front of serving up our app without a proxy to do it. hate to eject the config.

@filipesilva also — should this have a «this doesn’t work yet» marker somewhere?

I spent a few days trying to get this to work — I assumed the story doc’s meant it was usable.

#6493 added support to have the proxy config in .angular-cli.json , so that bit is sorted.

@chadbr the story described in https://github.com/angular/angular-cli/wiki/stories-proxy is working, and has been working for a long time, to the best of my knowledge. I have to suppose you did some modifications there. What were they?

So the remaining problem is that incoming connections when —host=0.0.0.0 is used? You might need to use —public-host/—disable-host-check as Webpack not enforces it (see #6173).

Ultimately though, you should really check out https://webpack.github.io/docs/webpack-dev-server.html#proxy as the proxy doc suggests (or the newer https://webpack.js.org/configuration/dev-server/#devserver-proxy). We only enable passing on these options, webpack provides the functionality proper.

@filipesilva — sorry, I misread your comment above —

I thought that meant the feature didn’t work 🙂

fwiw, I can’t get redirects to work when it goes to a public https host — but it works great locally.

Maybe off topic, but I’d greatly appreciate having all the ng serve options available in the config file.

If currently have to use ng serve —host 0.0.0.0 —public-host dev.domain.com:14200 —poll 1000 — i need polling because I’m running angular-cli on vagrant on windows (shared drive) and I want to serve the site to an in-house «public» web server (public-ish . protected from outside world but shared with a few other co-workers while we make updates to files). Maybe I’m doing something wrong, but it seems to work, its just frustrating that we can’t set up the settings in a config file and have to specify on the CLI every time.

Edit: a note on the port if anyone is curious, we run forward the port 4200 to the external port 14200 since we run several different vagrant machines for various testings.

Источник

ECONNREFUSED for proxy request from localhost to another localhost

To begin, I’m new to angular and I’m following a tutorial video step by step. I’ve been stuck on this issue for nearly 2 weeks and have spent many hours looking for solutions in other similar forums. I realize this is a common error, but after trying a couple dozen or so solutions but finding no success I figure I may as well post my experience and maybe it can shed some light on this problem many of us seem to be having.

The Issue

The error occurs while following along for the «Angular Tutorial #13» part of the video which starts around 1:42:00. I follow all steps exactly as shown in the video but I encounter the following error message in the terminal in which I run «npm start» :
[HPM] Error occurred while trying to proxy request /api/file.php from localhost:4200 to http://localhost:1234 (ECONNREFUSED)
My package.json scripts for «start»: «ng serve —proxy-config proxyconfig.json» and my proxyconfig.json contains:

In CMD I navigate to the folder «intro2angular» which is the root of «/test/api/file.php» and I run
php -S localhost:1234 prior to running npm start in the powershell in VisualStudioCode. Then I run npm start . Code compiles successfully. In Chrome, if I go to http://localhost:1234/test/api/file.php then the file is displayed in the browser. However, if I go to http://localhost:4200 and click an anchor which executes the code to request file.php then the [HPM] Error occurred while trying to proxy request /api/file.php from localhost:4200 to http://localhost:1234 (ECONNREFUSED) error is displayed in terminal. In the Network tab of Developer Tools in Chrome, when I check the Headers for file.php I see the follow:

Forgive me for being verbose in explaining every step I followed, but since I’ve seen several similar forum posts regarding the ECONNREFUSED error being raised while trying to use a proxy, I thought that including every minor detail may be necessary to distinguish the source of the error in this instance. If any more details/code is necessary I’m more than happy to include it.

Solutions I’ve tried thus far

Note that this is not a complete list, I’ve tried several other solutions but these seem to be the most common which have worked for others. Also, I’m not saying that I wouldn’t give these solutions another try as I am open to any and all suggestions.

  1. specifying random localhost ports for both the angular app and file.php
  2. using setTimeout to add a delay to the .getData() function call
  3. disabling firewall
  4. including the option «pathRewrite»: <«^/api» : «»>to proxyconfig.json

I appreciate any and all help/suggestions/discussions around this issue as I’ve had no success on my own and I am unable to continue with the angular tutorial until this issue is resolved. Thank you in advance.

Источник

Angular Cli proxy working in one env but return ECONNRESET in another

first time asking questions here so please let me know if I am missing any of the best practices.

I am working on an Angular 4 application that uses proxy to simplify the communication between front and back end of the application.

The proxy setting is the following:

In my main computer, when I run the part of the application that would call the proxy I get the following error.

The chrome console displays a 504 error.

The command I used to run all the servers

When the application is building, I can see that the proxy has been set up by the program, but the same error still happens.

However, when I try to run it on another computer that I have (exact same code, node setting, network environment etc.), the proxy is working.

I tried to replicate the error by making all application related setting identical between two computers (node version, npm version, clean installed all node packages and even pulled the application clean from github on both computers), but the error still persists on one but not the other.

Can someone make some suggestions on where should I look or what I should do next to identify the root cause of this problem? Thanks!

Things I’ve done so far:

  • Reinstall all npm packages
  • Restart Computer
  • Pulled application again from git
  • Running all the commands (for DB, server, and client) independently

Источник

Angular 8 application accessing proxied Spring Boot application on localhost over https

I have written a Spring Boot backend and an Angular 8 frontend that I am packaging together. So when deployed, both use the same port and this works nicely.

During develpoment, I want both applications to run separately and have set this up as follows:

application.yml

DataRestController.java

data.service.ts

In order for the frontend to be able to connect to the backend I have the following command defined in my package.json file:

proxy.conf.json

This all works perfectly. I can point my browser to http://localhost:10000/api/data and will receive the data in JSON format. Request by the frontend to http://localhost:4201/api/data are transparently forwarded to the backend URL and my angular application receives its data.

However, now I wanted to switch over to secure communication over https. I took the following steps:

I generated a PKCS12 file with a key pair and then extracted both the private key and certificate from this:

I copied the PKCS12 file to /src/main/resources/keystore/data.p12 in my backend and the two other files to /ssl/data.* in my frontend.

I added the following lines to my *application.yml

I also added a SecurityConfig.java file

If I now start my backend application, it no longer responds to the http URL, but it does answer on https://localhost:10000/api/data (I had to tell firefox to accept the self-signed certificate the first time I tried this, but afterwards it works flawlessly).

Now is where my troubles started, when I tried my frontend to talk to the backend over https 🙁

I added the following script to package.json

and created a new file proxy-secure.conf.json

When I run start-ssl my application is now served on https://localhost:4201 and it loads fine in the browser. However, when the angular application wants to access https://localhost:4201/api/data I get the following error in the console and the browser shows that a HTTP Status 500 is returned for the request.

After some googling I stumbled across this conversation on github and following the various advice given there I tried the following:

and I also changed the file extension so the file is now proxy-secure.conf.js

This produces the following output when the application starts up:

However, as soon as the front tries to access the backend, I still get the same error:

I am running out of ideas and google has been no help. I can’t imagine that I am the first person to try this setup. Is there anyway to tell the angular proxy to either not care about my self signed certificate or to tell it to trust that certificate?

If I do a ng build —prod and a mvn clean install (which thanks to maven-resources-plugin copies the frontend’s dist folder into classes/static of the char and then run the Spring Boot Application using java -jar data-0.0.1-SNAPSHOT.jar everything works:

I can access data using my browser by going to https://localhost:10000/api/data and get my JSON raw data. I can also go to https://localhost:10000/ to launch my angular app and it has no difficulty directly accessing above JSON data over https.

So my setup works in production but I cannot get it to run in my development configuration with the angular proxy.

Edit: to report about trying out the suggestions from the SO article Berk Kurkcuoglu linked to

As far as I can tell, that article describes how to enable SSL (something which I had no problem with), but still, it was worth a shot:

Источник

Понравилась статья? Поделить с друзьями:
  • Error occurred while saving data перевод
  • Error occurred error code 31 installation of the virtual network adapter device driver failed
  • Error occurred while refreshing the cache for directory
  • Error occurred during user certificate authentication please contact administrator
  • Error occurred while reading the file перевод