You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

开发环境正常,生产环境(Nginx+Gunicorn)中JS $.post请求报错

开发环境正常的JavaScript $.post请求在Nginx+Gunicorn生产环境报错

我的JavaScript代码在开发环境运行正常,但部署到Nginx+Gunicorn的生产服务器时,$.post请求抛出错误,无法获取视图返回的数据,页面无内容显示。

相关代码

JavaScript代码

<script>
        const findLoc = () => {
             const success = (position) => {
                const latitude = position.coords.latitude;
                const longitude = position.coords.longitude; 
                var data = {'latitude': latitude,
                            'longitude': longitude };
                data.csrfmiddlewaretoken = $('input[name=csrfmiddlewaretoken]').val();
                console.log('Location is on');
                console.log(data);
                document.getElementById("LocationLat").innerHTML = latitude;
                document.getElementById("LocationLon").innerHTML = longitude;
                $.post("gps/", data,function(response) {
                            // La réponse est maintenant disponible dans la variable 'response'
                            console.log('Réponse reçue:', response);
                            document.getElementById("postdata").innerHTML = response;
                            $('.spinner-border').hide();
                            
                        // Faites quelque chose avec les données, par exemple mettre à jour le contenu de la page
                        }).fail(function(xhr, status, error) {
                            // En cas d'échec de la requête, affichez l'erreur
                            console.log('Erreur lors de la requête:', status, error);
             });
            }
    
            const error = () => {
                console.log('Location gathering Not allowed')
                $('.spinner-border').hide();
                document.getElementById("postdata").innerHTML ="Activate position in your browser !"
            }
    
            navigator.geolocation.getCurrentPosition(success,error);
        }
        
      </script>

报错来自上述代码中的$.post语句。

urls.py代码

urlpatterns = [
    path('admin/', admin.site.urls),
    path('gps/',views.home_view),
]

views.py代码

def home_view(request):   

        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]
        else:
            ip = request.META.get('REMOTE_ADDR') 

        if request.method == 'POST':
            Latitude = float(request.POST.get('latitude'))
            Longitude = float(request.POST.get('longitude'))
            context = aviationweatherapi.getStationInfo(None,Latitude,Longitude)
            print ("Get airports list around current GPS location")
            #print (context)
            templateview='partial-results.html'
            
        
        else:
             #The request is GET
             list ='LFHC,LFHN,LFHS,LFJD,LFKY'
             context = aviationweatherapi.getStationInfo(list, None, None)
             context.update({'IP':ip})
             print ("Get all airports")
             templateview='acceuil.html'
        
        context.update({'IP':ip})

        return render(request,templateview,context)

排查与解决方案

1. 验证CSRF令牌有效性

  • 打开浏览器控制台,打印$('input[name=csrfmiddlewaretoken]').val(),确认令牌不为空且有效。
  • 若生产环境域名与后端不一致,在Django的settings.py中添加信任域名:
    CSRF_TRUSTED_ORIGINS = ['https://你的生产域名.com']
    

2. 修正请求路径

  • 开发环境的相对路径gps/可能在生产环境因URL层级问题失效,改为绝对路径/gps/(开头加斜杠)。
  • 更可靠的方式是用Django的URL反向解析:给urls.py的path添加name参数:
    path('gps/', views.home_view, name='home_view')
    
    然后在模板中替换JS里的请求路径为{% url 'home_view' %},确保路径始终正确。

3. 检查Nginx与Gunicorn配置

  • 确保Nginx正确转发POST请求到Gunicorn,配置示例:
    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
    
  • 查看Nginx错误日志(如/var/log/nginx/error.log)和Gunicorn日志,排查请求是否被拦截或服务器内部报错。

4. 给视图函数添加异常捕获

  • 生产环境Django默认隐藏详细错误,在POST分支添加异常处理,便于定位问题:
    if request.method == 'POST':
        try:
            Latitude = float(request.POST.get('latitude'))
            Longitude = float(request.POST.get('longitude'))
            context = aviationweatherapi.getStationInfo(None, Latitude, Longitude)
            print("Get airports list around current GPS location")
            templateview='partial-results.html'
        except Exception as e:
            print(f"POST请求处理错误: {e}")
            return JsonResponse({'error': str(e)}, status=500)
    
  • 检查aviationweatherapi.getStationInfo在生产环境是否能正常调用,是否存在依赖缺失或API访问限制。

5. 查看前端请求详情

  • 在浏览器开发者工具的Network标签中,查看$.post请求的状态码和响应内容:
    • 403状态码:CSRF验证失败
    • 404状态码:请求路径错误
    • 500状态码:服务器内部错误,结合后端日志排查

内容的提问来源于stack exchange,提问作者Heavy PC

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 21:30:26