Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read timed out. error while sending a POST request to a node.js API

Tags:

python

node.js

I have a node.js API as below to which I send a POST request from python as below,the issue am facing is if I remove the headers={"Content-Type": "application/json"} the POST goes thorugh,if not i get a Read timed out. error, can anyone provide guidance on how to fix this timeout error ?

node.js endpoint

app.post("/api/bats_push",(req, res) => {
        //console.log("Calling bats_push...")
        const d = {
            method: req.method,
            headers: req.headers,
            query: req.query,
            body: ''
        }

        req.on('data', (c) => {
            //console.log(c)
            d.body = d.body + c
        });

        req.on('end', () => {
            DATA.push(d);
            res.end('Saved BATS job details');
            //res.status(200).json({
              //message: "Saved BATS job details",
              //posts: req.body
          //}); 
        });
});

Python POST

try:
json"},timeout=10.0)
    r = requests.post(webhook_url,data=json_data.encode("utf8"),verify=False,headers={"Content-Type": "application/json"})
    print "posted"
    print(r.status_code, r.reason)
    print r.url
    print r.text
except Exception as e:
    print (e)

Error:-

  InsecureRequestWarning)
HTTPSConnectionPool(host='company.com', port=443): Read timed out. (read timeout=10.0)
like image 360
Ritz Avatar asked Oct 09 '19 23:10

Ritz


1 Answers

I seems that you are using express.js. I believe that your problem is, that body is actually already parsed. You can check it by reading req.body. The situation is caused because express.js already read whole body (due to the content type) and trying to read body again will cause timeout (event data and event end are not emitted). There are several ways how to fix it.

  1. disable express.js body parser - or reconfigure it to ignore json

  2. remove reading body code and use directly req.body

app.post("/api/bats_push",(req, res) => {
        //console.log("Calling bats_push...")
        const d = {
            method: req.method,
            headers: req.headers,
            query: req.query,
            body: req.body
        }

        DATA.push(d);
        res.end('Saved BATS job details');
});

like image 78
Tomas Avatar answered Nov 02 '22 22:11

Tomas