Home > Net >  How can I retrieve my post request using JavaScript
How can I retrieve my post request using JavaScript

Time:11-17

I have two projects, the first one is Node.JS.

        jsonobj = JSON.stringify(generateMockData)
        xhrToSoftware.send(jsonobj);
        xhrToAPI.open("POST", "http://127.0.0.1:8000/path/", true);
        xhrToAPI.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
        xhrToAPI.send(jsonobj);

It's sending data to the second project Django Python. I can receive the data using my views.py.

post_data = json.loads(request.body.decode("utf-8")) 
value = post_data.get('data')
print(value)

But I want to directly get the data from Node.JS to my Django Templates (javascript or jquery) is that possible?

for example:

<script>
 //get the data that posted by the node.js
</script>

UPDATE:

I tried using the answers below like this one:

fetch('http://127.0.0.1:8000/path/')
    .then(response => response.json())
    .then(data => {
        console.log(data);
    })
    .catch(error => console.error(error));

but I'm having an error it says that:

SyntaxError: Unexpected token '<', "<!-- 
 
<d"... is not valid JSON

I think that's because I'm returning an html file in my views.py:

def data(request):
    if request.method == 'POST':
        post_data = json.loads(request.body.decode("utf-8"))  # for simulation
        value = post_data.get('data')
    return render(request, 'waterplant/iot/data.html')

so, I change it to jsonresponse like this:

def data(request):
    if request.method == 'POST':
        post_data = json.loads(request.body.decode("utf-8"))  # for simulation
        value = post_data.get('data')
        return JsonResponse({"msg": value}, status=200)

After that I'm having an error ValueError: The view views.data didn't return an HttpResponse object. It returned None instead. I think that's because the value is empty yet. How can I prevent that? If I send a data using my Node.JS I want to return it as return JsonResponse({"msg": value}, status=200) Or you have any idea that I can access the data directly in my Django Python templates <script> here </script>

CodePudding user response:

  • Basic js fetch()

If you use method "GET":

fetch('http://127.0.0.1:8000/path')
    .then(response => response.json())
    .then(data => {
        console.log(data);
    })
    .catch(error => console.error(error));

If you use method "POST":

fetch(`http://127.0.0.1:8000/path`, {
            method: "POST",
            headers: {"Content-type": "application/json; charset=UTF-8"},
            body: data
        })
        .then(response => response.json())
        .then(json => {
            console.log(json);
        })
        .catch(error => console.error('Error on fetch() call:\n', error));
  • Hope it could be useful!

CodePudding user response:

If a get request is to be made from your webpage use fetch()

fetch('http://127.0.0.1:8000/path')
     .then((response) => response.json())
     .then((data) => console.log(data));
  • Related