1

I have a python script returning a string which I want to display on my web site

Here is the working python script

import requests
import json

url = "http://localhost:3000"
data = {'msg': 'test message'}
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
r = requests.post(url, data=json.dumps(data), headers=headers)

I want the msg ("test message") to be sent to the client

Currently I have server.js and client (index.html). When hardcoding a message in server.js, it will be shown in index.html. However, when trying to send the python message (that server.js can receive), it doesn't get recognized (msg undefined)

server.js

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
  //send the index.html file for all requests
  res.sendFile(__dirname + '/index.html');
});

 app.post('/',function(req,res){
        var msg=req.body.msg;
        console.log("python result: " + msg);
        io.emit('message', msg);
 });

http.listen(3000, function(){
  console.log('listening on *:3000');
});

index.html (i want to show the message here)

<html>
<head></head>

<body>
  <div id="message"></div>

  <script src="/socket.io/socket.io.js"></script>
  <script>
    var socket = io();

    socket.on('message', function(msg){
      console.log(msg);
      document.getElementById("message").innerHTML = msg;
    });
  </script>
</body>
</html>

The goal is that every time python script is executed, the server will send the python msg to the client

  • 1
    Does this answer your question? [How do I consume the JSON POST data in an Express application](https://stackoverflow.com/questions/10005939/how-do-i-consume-the-json-post-data-in-an-express-application) - accepted answer points out that you need have proper middleware in place (bodyParser or express.json() depending on what express version you are running) – rasjani Jun 28 '23 at 16:34
  • 1
    @rasjani you are right - ```app.use(express.json());``` was missing. working now – Genesis1337 Jun 28 '23 at 17:14

0 Answers0