Axios proxy не работает

Axios, запрос прокси вроде не работает

Кажется, что библиотека axios не работает axios образом, и я не знаю, что не так.

Сначала объясню. Я новичок в axios и компания, в которой я работаю, настроила сервер API, используя nGinx с proxy pass .

Допустим, сервер API находится в домене: https://www.api.com а конечные точки api расположены в https://www.api.com/api/ .

Читайте также:  Почему у меня не работает css

Затем мы собираемся создать приложение SSR, используя библиотеку axios для выполнения запроса к этому серверу, но суть в том, чтобы использовать proxy settings axios таким образом, чтобы запросы finally не были такими: https://www.api.com/api/endpoint но вот так: https://www.js-app.com/api/endpoint .

Итак, в настоящее время у меня есть следующий класс:

Итак, теперь, когда я использую этот класс из другого места в моем приложении, используя код, подобный этому:

В консоли браузера я получаю сообщение об ошибке 404, и это потому, что axios все еще запрашивает вызов API у моего локального хоста, а не с удаленного сервера.

Я получаю такую ошибку:

Также настройки axios внутри Interceptor запроса таковы:

Так ты думаешь, я что-то не так делаю? Вы думаете, я пытаюсь достичь чего-то, что не возможно? Есть ли выход из этой ситуации? Есть идеи, как подойти к этому вопросу?

Источник

Axios proxy is not working. #2072

Comments

pumanitro commented Mar 31, 2019

Describe the bug
I have installed anyProxy 3rd party proxy ( http://anyproxy.io/en/#install )
When I type anyproxy in my command line then my proxy starts on http://localhost:8001
and I have also preview of proxy status on http://localhost:8002.

On the Frontend site, I’m using axios like:

But the request is omitting proxy and is sent directly:

It behaves like the axios proxying functionality would not be even working.

I also tried stuff like:

But it gives me the same result as the previous one.
Also tried npm dependency called «axios-https-proxy-fix», but with the same result.

Expected behavior
Proxying request to the proxy server.

Environment:

  • Axios Version «axios»: «0.18.0»,
  • OS: Win 10
  • Browser Chrime
  • Browser Version 73.0.3683.86

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

SwiTool commented May 7, 2019 •

I tried the proxy param, which is apparently not supported in browser, but at least I tried :

And also with the httpsAgent param :

None of them work.

k0t0fey commented May 17, 2019

+1
proxy option not working with https
Any ideas how to solve this problem?

jerrwy commented May 23, 2019

kingkong404 commented Jun 22, 2019

+1 not working in version .19

Stas-Buzunko commented Jun 24, 2019

i did 3 things that got it working.

  1. updated node to v11+
  2. added —tls-min-v1.0 flag like this node —tls-min-v1.0 index.js
  3. updated axios to .19

first 2 didn’t help without the last one.

SwiTool commented Jun 25, 2019 •

i did 3 things that got it working.

  1. updated node to v11+
  2. added —tls-min-v1.0 flag like this node —tls-min-v1.0 index.js
  3. updated axios to .19

first 2 didn’t help without the last one.

Thank you for that ! Next time i’ll work on proxies i’ll take a look.

I have been struggling for an entire day trying to make this work, that was in april, but I finally switched to another library.
Proxies work very well with node-fetch combined with https-proxy-agent .

diegolaciar commented Sep 16, 2019

Axios default.proxy settings don’t work on Chrome.
Any workaround for this?

habmukandu commented Nov 12, 2019

Axios (v.19) is not working with our corporate proxy for https requests. We use a squid proxy and it returns a protocol error in our case.

You can reproduce the error in node (with a public squid proxy) using latest Axios and an Axios version using ‘https-proxy-agent’:

run:
npm install axios axios-https-proxy-fix

create file ‘index.js’ with content:

run
node index.js

Then you can see in console log that Axios fails with a protocol error while the modified Axios version using https-proxy-agent succeeds.

kraiz commented Dec 19, 2019

I was able to make requests to some servers but not all. Seems like it depends on the servers cipher suites. For all servers with just cipher suites beginning with ECDHE_ the request failed.

Following the axios’ code we need to make sure that this if expression is false: http.js#L100 . I fixed the problem with this axios configuration (applying it to @habmukandu code above):

tldr: setup httpsAgent and (!) set proxy: false .

christianp86 commented Jan 2, 2020

williamdarkocode commented Jan 3, 2020

none of these shite solutions work!

ch-benard commented Jan 15, 2020

@kraiz Tks ! Your solution works for me.

adam-s commented Feb 10, 2020 •

axios-https-proxy-fix will cause Axios to hang indefinitely without timeout or throwing an error conflicting with other libraries in npm. Using node-tunnel (https://github.com/koichik/node-tunnel) to create an agent also works.

nsharma1989 commented Feb 27, 2020

Hi Is there any known solution to this yet.. I have tried a bunch of stuff but they are not working

adam-s commented Feb 27, 2020 •

@nsharma1989 Use node-tunnel to create an agent that will tunnel through all the proxies. Add the agent as a property to the request object configuration. Post an example of the request you are trying to make.

nsharma1989 commented Feb 27, 2020 •

Hi @adam-s , Thank you for the prompt response I did tried that too however no success. could you help me pointing to a code snippet may be? Thank you
Also I want to ignore the cert_invalid_errors .

adam-s commented Feb 27, 2020

My proxy is over http while the call to github is over https so I use the appropriate method. I read that with tunnel setting the port which is 443 over https might be required, however, it worked without setting it in my case.

nsharma1989 commented Feb 27, 2020

@adam-s tried the same but my https request still gives t::ERR_CERT_AUTHORITY_INVALID
after adding rejectUnauthorized: false

adam-s commented Feb 27, 2020

@nsharma1989 Sounds frustrating. I can’t help beyond my own success using node-tunnel with axios. I don’t know if a server can force using a signed certificate or not. I was reading about self-signed certificates which need to be shared between the client and server.

I assume you placed rejectUnauthorized: false on the agent configuration

Sorry I can’t be more help.

shasu01 commented Mar 19, 2020

I have proxy in my package.json and I call my endpoint using axios.get (‘/get/GetAllJobs’)
On local dev it works, but not after npm run-script build

chinesedfan commented Apr 6, 2020

Let me make some conclusions,

  • For the original issue, as I answered in stackoverflow, axios’s config.proxy is Node.js only. I think it is meaningless in browsers. You can check lib/adapters/xhr.js and will find nothing related to proxy there.
  • For other users discussed proxies in Node.js, there were two main ways.
    • When using package https-proxy-agent , better to disable the proxy by proxy: false . See @kraiz’s comment.
    • When using koichik/node-tunnel, you can ignore the cert_invalid_errors. See @adam-s’ comment.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

axios: запрос https через прокси

Я пытаюсь использовать Axios с прокси-сервером для вызова https:

Все прокси-серверы, которые я использую, находятся в Соединенных Штатах, являются высоко анонимными, с поддержкой HTTP и HTTPS.

Я получаю эту ошибку:

Чтобы убедиться, что проблема связана с axios, а НЕ с прокси, я попытался это сделать:

Это полностью работает просто отлично.

Как настроить axios для работы с прокси и https URL?

8 ответов

Поддержка прокси-сервера Axios https прерывается при использовании прокси-сервера https. Попробуйте пройти через прокси [httpsProxyAgent][1] используя http.

В качестве альтернативы есть ветвь Axios, которая включает это: axios-https-proxy-fix, но я бы порекомендовал первый метод для обеспечения последних изменений Axios.

Попробуй это. Это работа для меня.

npm установить axios-https-proxy-fix

В https-proxy-agent и node-tunnel решения действительно работали для меня, но оба они не поддерживают условное проксирование с использованием NO_PROXY.

Я нашел global-agent как лучшее решение в моем случае, поскольку он изменяет основные объекты http и https и будет автоматически применяться к любой библиотеке, которая их использует, включая axios , got , request , и т.д.

Использование очень простое.

Добавить import ‘global-agent/bootstrap’; к точке входа ( index.ts ) сервера.

Запустите эти переменные env и убедитесь, что HTTP_PROXY, HTTPS_PROXY НЕ находятся в env.

Источник

Как настроить прокси при использовании axios для отправки запросов?

Я использую пакет под названием «одновременно» для одновременной работы моего клиента и сервера на локальном хосте. Клиент работает на порту 3000, а сервер — на порту 5000. Я установил прокси в package.json сервера следующим образом:

Но когда я делаю запрос от клиента следующим образом:

Там написано: POST http://localhost:3000/api/users 404 (Not Found) . Я не понимаю, почему, но несмотря на настройку прокси, axios продолжает делать запросы на порт 3000 вместо порта 5000. В чем проблема?

3 ответа

Я правильно понял. То, что я сделал, было:

1) изменить axios.post(‘/api/users’, body, config); на axios.post(‘http://localhost:5000/api/users’, body, config);

2) Затем в экспресс-маршруте «users» на стороне сервера добавьте функциональность CORS, установив пакет nors «cors», а затем добавив следующие строки:

Я просто хочу сказать, что решение добавления Cors не является решением. Вам нужно включить прокси «proxy» : «https://localhost:5000» в package.json, вам может потребоваться перезапустить или сделать что-то или другое — но если вы решите использовать вместо этого cors, вы разрешите любому получить доступ к вашему API. Это означает, что ваша база данных широко открыта для людей, с которыми можно возиться. Пароли, электронные письма, пользователи и т. Д. Все это взломано.

Насколько я понял ваш вопрос, вам нужно обратиться к документам разработчика Axios. на время. установите этот флажок

Источник

practical proxy question #126

Comments

husayt commented Mar 16, 2018 •

Axios module working with proxy module offers a lot of great features. Main problem is lack of examples to bring these features to surface, I am sure most of users don’t even know about 90% of those features.

For example I have this requirement:

My nuxt website needs to connect to http://dataserver:com:4444 .
I have two setups:

  1. in dev mode nuxt server running on http://locahost:3000 with /api proxying to http://dataserver:com:4444
  2. in prod mode website is statically generated (via generate) and deployed to run on http://dataserver:com:80 with /api proxying to http://dataserver:com:4444

should call http://dataserver:com:4444/orders if it is prod mode or if it SSR in dev mode. On client side call of dev mode it should call http://locahost:3000/api/orders (which is a proxy url for
http://dataserver:com:4444 )

This is my config

What am I missing?
It works as expected in dev mode, but in in prod mode it calls http://dataserver:com:4444/api/orders , instead of http://dataserver:com:4444/orders (Notice extra api in the url)

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

mdsaudali365 commented Sep 19, 2018

I was stuck on axios and proxy module implementation in my project, but your question cleared the path for me. I totally agree with you that it would be great to have some officially integrated examples:)

zoellner commented Jan 16, 2019 •

I was also missing some data flow diagrams to wrap my head around where all the prefix and proxy magic is happening and which configuration option takes precedence.

Another missing piece is the port configuration when using something other than 3000 for local dev since it seems to be hardcoded in a few places. E.g. for nuxt itself it is sufficient to set server.port or env.PORT in nuxt.config.js but the axios module seems to ignore those and still use 3000.
It has to be set at the npm level to work — a note about that should be added to the documentation that mentions

Can be customized with API_PREFIX, API_HOST (or HOST) and API_PORT (or PORT) environment variables.

That is actually not quite correct anyways since setting API_PREFIX has no effect if API_URL is set but proxy is not enabled. It does only work when either API_HOST is not set (then used for both baseUrl as well as browserBaseURL) or when set but also proxy enabled (then used for browserBaseURL).

One more gotcha is that while the documentation for axios options lists baseUrl it can’t actually be set using axios.baseUrl in nuxt.config.js . It’s basically a read-only option that can only be set through yet another environment variable that has to be at the npm level — API_URL .
Somewhat unfortunate naming here as well since axios’ baseUrl is the baseUrl for the API but nuxt baseUrl is for the nuxt backend which might be different servers.

Also missing an explanation on how to setup different targets based on the environment (dev/prod). I believe this isn’t easily possible through nuxt.config.js but has to be done through npm-level environment variables.

Another useful hint in the documentation would be for debug logging using the environment variable DEBUG=nuxt:*

My final Setup

The final configuration for me is as follows, hope it helps others.

Источник

Оцените статью