Ajax 502 ошибка

I get 502 Bad Gateway for some requests on my server. I get it for some particular AJAX requests but if I replay the failed request in the console, it works (wtf). In nginx/error.log it says

[error] 13867#0: *74180 recv() failed (104: Connection reset by peer) while reading response header from upstream

My website is in PHP. Thanx

asked Feb 7, 2014 at 20:28

Michal Artazov's user avatar

Michal ArtazovMichal Artazov

4,3788 gold badges25 silver badges38 bronze badges

2

I had similar problem on wordpress site. add these lines inside http block of /etc/nginx/nginx.conf file.

fastcgi_temp_file_write_size 10m;
fastcgi_busy_buffers_size 512k;
fastcgi_buffer_size 512k;
fastcgi_buffers 16 512k;

If it still not working also add this line

 client_max_body_size 50M;

answered Mar 11, 2019 at 5:15

Tharindu Wickramasinghe's user avatar

I had similar problem with my gitlab setup on nginx. What helped solve my problem was to higher max client’s body size by client_max_body_size 50m directive inside http block of /etc/nginx/nginx.conf file.

answered Feb 8, 2014 at 10:05

svobol13's user avatar

1

Comments

@sergiodebcn

peterwooyan

added a commit
to peterwooyan/laravel-enviornment
that referenced
this issue

Jan 16, 2023

@peterwooyan

When using the Laravel DebugBar with the `capture_ajax` flag set to `true`, its AJAX request monitoring exceeds the FastCGI buffer limit. This results in Nginx throwing a 502 Bad Gateway exception. 

This PR increases the size of the buffer. While it is not guaranteed to fix the problem, the increased buffer size should solve the issue for most developers. Further discussion on this subject can be [found in this issue on the DebugBar repo](barryvdh/laravel-debugbar#251)

LukeTowers

added a commit
to wintercms/wn-vapor-plugin
that referenced
this issue

Jul 31, 2023

@LukeTowers

What Does 502 Bad Gateway Mean?#

A 502 Bad Gateway indicates that the edge server (server acting as a proxy) was not able to get a valid or any response from the origin server (also called upstream server). This can occur for a few reasons, which we’ll discuss in the section below. If one of KeyCDN’s edge servers receive a 502 Bad Gateway response from your origin server, KeyCDN will return a 500 Origin Not Reachable page. To get a better understanding on how KeyCDN handles certain error codes, check out our CDN Error Codes page.

How to Solve 502 Errors — for Web Developers#

As a web developer or owner of the website, there are a few reasons why you may be experiencing a 502 Bad Gateway error on your origin server. Therefore, you may need to try various methods to resolve the issue. Reference the list of suggestions below:

Check if your FQDN (fully qualified domain name) is resolving correctly by using our DNS test tool.
Verify if your server is reachable by using a ping test or trace-route.
Check your firewall logs if you are seeing unusual drops.
If you’re a Cloudflare user, try disabling it as once you’ve reached a certain limit Cloudflare will return a 502 Bad Gateway error to your visitors.

How to Solve 502 Errors — for Visitors#

If you’re a website visitor and experience a 502 Bad Gateway error then there is also a few things you can try to resolve it. Although the primary issue will almost always be the responsibility of the web developer, visitors can try the following:

Perform a hard-refresh in your browser. On Macs, this is done by pressing Cmd + Shift + R.
Clear your browser cache and delete cookies. Your browser may be holding on to certain files that were saved once you visited the website with a 502 error.
Restart your computer/networking equipment
Change your DNS servers. If you’ve never changed them in the past you likely still have the default servers assigned to you by your ISP, try using open DNS servers such as Google’s Public DNS.

Ajax — это технология, которая позволяет избежать перезагрузки страницы при обмене данными между браузером и сервером. Однако, при работе с Ajax-запросами возможны ошибки, например, ошибка 502/500.

Ошибка 502/500 может возникнуть по нескольким причинам. Одна из них — это проблемы с сервером. Если сервер временно отключен или перегружен, то при отправке запроса браузер не получает ответ и выдает ошибку 502/500.

Другая причина возникновения ошибки 502/500 — это проблемы на стороне клиента. Например, если на странице, с которой производится запрос, используется устаревшая библиотека jQuery, то может возникнуть конфликт между версиями, что приведет к ошибке.

Еще одна причина возникновения ошибки 502/500 — это использование неверных параметров запроса. Если запрос содержит неправильные параметры, то сервер не сможет вернуть корректный ответ, что приведет к ошибке.

Чтобы избежать ошибок 502/500 при работе с Ajax-запросами, необходимо следовать нескольким правилам. Во-первых, необходимо проверить состояние сервера и убедиться, что он работает корректно. Если сервер перегружен или недоступен, необходимо подождать некоторое время и попробовать отправить запрос позже.

Во-вторых, необходимо обратить внимание на версии используемых библиотек. Если на странице используется jQuery, необходимо убедиться, что версии совместимы. Если возникает конфликт между версиями, необходимо обновить библиотеку или включить новую версию.

В-третьих, необходимо проверить правильность параметров запроса. Необходимо убедиться, что все необходимые параметры объявлены и переданы правильно. Если возникают проблемы с параметрами, необходимо проверить код запроса и исправить ошибки.

В заключение, следует отметить, что при работе с Ajax-запросами возможны различные ошибки, включая ошибку 502/500. Чтобы избежать этих ошибок, необходимо проверять состояние сервера, убедиться в совместимости используемых библиотек и проверять правильность параметров запроса. Эти меры позволят избежать ошибок и обеспечить более эффективную работу с Ajax-запросами.

Some time ago, I went back to using Valet for local development, and I’ve been happy with it since. Up until sometime last week, I’d yet to run into any problems.

Fix Valet, WordPress, Ajax, Bad Gateway: Valet

But when working on a WordPress plugin that imports data using admin-ajax, I kept getting a curious message in the console no matter how large or small the data was. Specifically, I was getting an error about “502 (Bad Gateway).”

The server, while acting as a gateway or proxy, received an invalid response from an inbound server it accessed while attempting to fulfill the request.

And if you try to diagnose it based on that definition, you won’t get very far. It’s not that it’s wrong, but it’s that you need to modify your server configuration.

Luckily, it’s easy. Or it’s likely easy.

Before sharing the fix, I’ll say that this sent me down a deep rabbit hole of all kinds of Nginx configurations, reverse proxy information, PHP-FPM, and on and on. If you opt to Google for that, be aware that you’ll likely come across them, too.

Fix Valet, WordPress, Ajax, Bad Gateway: Nginx

And the truth it, maybe that’s what your problem is (I’ll share the links at the bottom of the post), but my particular fix was much easier than that.

Assuming that you’re using macOS, navigate to the .valet directory in your terminal with the following command:

$ cd ~/.valet

Once there, look for the Nginx directory and then enter:

$ ls Nginx

Check to see if you see a file for your specific development server. Note that I use the link command over the park command so I’ll have something like wptrunk.dev. If you don’t have a file there, that’s likely the problem.

And if so, enter the following command:

$ touch Nginx/your-site.dev

Where your-site.dev is whatever the domain that’s causing the problem.

Fix Valet, WordPress, Ajax, Bad Gateway: Atom

Next, open that particular file in your text editor of choice and add two lines:

fastcgi_buffers 16 16k;
fastcgi_buffer_size 32k;

Save the file then restart Valet in the terminal with a simple:

$ valet restart

Then retry the problem that you were experiencing. For me, increasing (or defining) the buffer sizes to the above values worked. You may need larger values so, as they say, YMMV.

The point is, the fix may not be extraordinarily complicated so before you start writing an entire custom configuration file from scratch, try tinkering with these values first.

Related Links

  • 502 Errors on admin-ajax.php
  • admin-ajax.php: 502 Bad Gateway
  • WordPress admin URLs return 404
  • Troubleshooting Valet on Sierra
  • Starting with Laravel Valet on OSX
  • upstream sent too big header while reading response header from upstream

Понравилась статья? Поделить с друзьями:
  • Al006 ошибка delta
  • Aisino v71 ошибка печати
  • Al 60 ошибка на пеканиске
  • Ais ошибка на потоке
  • Airwheel z3 ошибка 7