1

I am running a Python code to post some data to my Node.js server. Upon receiving the data at the server, i need the Node.js server to send a custom response back to the Python along with the status code.

I am using pure Node.js. No frameworks like Express or Hapi is used. My code works perfectly but i am not able to print the desired message.

Part of my Python Code used to post the data

import requests, json
payload = {
                     "DevId" : 'R',
                     "Sdata" : 'S',
                     "TimeS" : 'T',
                     "RSSI"  : 'U'
            }
jsonPayload=json.dumps(payload)
headers = {'Content-Type': 'application/json'}          
post_res =requests.post(url='http://localhost:5555/',data=jsonPayload, headers=headers)
print post_response

What i have tried at the Node.js server are.

1.

response.writeHead(200, { 'Content-Type': 'text/plain'});
response.end('Server has received the data')

Output : <Response [400]>

2.

response.writeHead(200, { 'Content-Type': 'text/plain','Trailer': 'Server-Message' });
response.addTrailers({ 'Server-Message': 'Ok' });
response.end();

Output : <Response [200]>

3.

var message = 'Invalid Device ID';
response.writeHead(400, message, {'content-type' : 'text/plain'});
response.end(message);

Output : <Response [400]>

I didn't get any error for the above code, so i don't know what i am doing wrong.

My desired output is, along with the status code i need to print a custom message received from the server, in the terminal i am executing the Python code.

<Response [200]> "The server has received the message"

1 Answer 1

1

Try printing post_response.text as well as post_response as per requests documentation

example:

server.js:

const http = require('http')

const server = http.createServer((req,res) => {
  res.setHeader('Content-Type', 'text/html');
  res.writeHead(200, { 'Content-Type': 'text/plain'});
  res.end('Server has received the message');
})

server.listen(3000, (err) => {
  if(err) {
    console.error('error');
  }

  console.log('server listening on port 3000');
})

response.py:

import requests

r = requests.post('http://localhost:3000', { 'Content-Type': 'application/json'});

print(str(r) + " " + r.text)
Sign up to request clarification or add additional context in comments.

1 Comment

This works fine. I had read the Node.js documentation several times but didn't find any solution. And never thought i could find it in pythons documentation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.