Search code examples
javascriptpythondjangodjango-channels

Is it possible to get the payload data of a JavaScript socket io and print it using Django?


I have this JavaScript project that uses socket io and console the data.

const   = generateMockData(deviceId);
        console.log(payload)
        io.of("/").emit("data", JSON.stringify(payload));

And this is the generated mock data

function generateMockData(deviceId) {
  const contaminants = [
    {
      id: 9,
      ave: chance.floating({ min: 5, max: 5.5, fixed: 7 }),
      ave_reduction: chance.floating({ min: 0, max: 1, fixed: 1 }),
    },
    {
      id: 10,
      ave: chance.floating({ min: 5, max: 5.5, fixed: 7 }),

      ave_reduction: chance.floating({ min: 0, max: 1, fixed: 1 }),
    },
    {
      id: 14,
      ave: chance.floating({ min: 5, max: 5.5, fixed: 7 }),
      ave_reduction: chance.floating({ min: 0, max: 1, fixed: 1 }),
    },
    {
      id: 15,
      ave: chance.floating({ min: 5, max: 5.5, fixed: 7 }),
      ave_reduction: chance.floating({ min: 0, max: 1, fixed: 1 }),
    },
  ];

socket io listening to this port

const port = process.env.PORT || 3000;
server.listen(port, () => {
  console.log(`listening on http://localhost:${port}`);
});

in my console it looks like this

 contaminants: [
    { id: 9, ave: 5.4897571, ave_reduction: 0.5 },
    { id: 10, ave: 5.4942647, ave_reduction: 0.7 },
    { id: 14, ave: 5.316183, ave_reduction: 0.5 },
    { id: 15, ave: 5.0806739, ave_reduction: 0.9 }
  ],

is it possible to pass this payload data (console data) to Django? I tried using httpresponse in Django but it's not getting the data I want. The javascript and the django are in different projects.

from django.http import HttpResponse  
response = HttpResponse("http://localhost:3000/")
        print(response)

print response

<HttpResponse status_code=200, "text/html; charset=utf-8">

my urls.py

urlpatterns = [
    path('', index)
]

views.py

def index(request):
    return render(request, 'base.html', context={'text': "data"})

Solution

  • const port = process.env.PORT || 3000;
    server.listen(port, () => {
        //POST payload to django
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.open("POST", "https://your-django-page/app-name");
        xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
        xmlhttp.setRequestHeader("X-CSRFToken", csrftoken);
        xmlhttp.send(JSON.stringify({ "port": port }));
    });
                            
    

    views.py:

    def index(request):
        if request.method == 'POST':
            port = request.POST.get("port")
            return render(request, 'base.html', context={"text": "data", "port":port})
        return render(request, 'base.html', context={"text": "data", "port":port})
    

    urls.py

    urlpatterns = [
        path('', index, name="index")
    ]
    

    To avoid cross origin error:

    pip install django-cors-headers
    

    settings

    INSTALLED_APPS = [
        ...    
        'corsheaders',
        ...
    ]
    
    MIDDLEWARE = [
        ...
        'corsheaders.middleware.CorsMiddleware',
        ...
    ]
    ALLOWED_HOSTS=['*']
    CORS_ORIGIN_ALLOW_ALL = True