Python Flask Node.js failed to load resources 404

Hi I am trying to send data from node to python. I read this is possible via 2 server with express and Flask. However when I run the code I receive an error (see below)

Python script

from flask import Flask, request
import json

app = Flask(__name__)

@app.route('/')
def index():
    return "Flask server"

@app.route('/postdata', methods = ['POST'])
def postdata():
    data = request.get_json()
    print(data)
    # do something with this data variable that contains the data from the node server
    return json.dumps({"newdata":"hereisthenewdatayouwanttosend"})

if __name__ == "__main__":
    app.run(port=5000)

The Node script

var express = require('express');
var bodyParser = require('body-parser');
var request = require('request-promise');

var app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.get('/postdatatoFlask', async function (req, res) {
    var data = { 
        data1: "foo",
        data2: "bar"
    }

    var options = {
        method: 'POST',
        uri: 'http://localhost:3000/postdata',
        body: data,
        json: true // Automatically stringifies the body to JSON
    };

    var returndata;
    var sendrequest = await request(options)
    .then(function (parsedBody) {
        console.log(parsedBody); 
        returndata = parsedBody; 
    })
    .catch(function (err) {
        console.log(err);
    });

    res.send(returndata);
});

app.listen(3000);

However if I now try to execute the post request with http://localhost:3000/postdatatoFlask I get the 404 error

PS C:\Users\danie\Desktop\nodepythonproject> node nodepython { StatusCodeError: 404 - "\n\n\n\nError\n\n\n

Cannot POST /postdata
\n\n\n" at new StatusCodeError (C:\Users\danie\node_modules\request-promise-core\lib\errors.js:32:15) at Request.plumbing.callback (C:\Users\danie\node_modules\request-promise-core\lib\plumbing.js:104:33) at Request.RP$callback [as _callback] (C:\Users\danie\node_modules\request-promise-core\lib\plumbing.js:46:31) at Request.self.callback (C:\Users\danie\node_modules\request\request.js:185:22) at emitTwo (events.js:126:13) at Request.emit (events.js:214:7) at Request. (C:\Users\danie\node_modules\request\request.js:1157:10) at emitOne (events.js:116:13) at Request.emit (events.js:211:7) at IncomingMessage. (C:\Users\danie\node_modules\request\request.js:1079:12) at Object.onceWrapper (events.js:313:30) at emitNone (events.js:111:20) at IncomingMessage.emit (events.js:208:7) at endReadableNT (_stream_readable.js:1064:12) at _combinedTickCallback (internal/process/next_tick.js:138:11) at process._tickCallback (internal/process/next_tick.js:180:9) name: 'StatusCodeError', statusCode: 404, message: '404 - "\n\n\n\nError\n\n\n
Cannot POST /postdata
\n\n\n"', error: '\n\n\n\nError\n\n\n
Cannot POST /postdata
\n\n\n', options: { method: 'POST', uri: 'http://localhost:3000/postdata', body: { data1: 'foo', data2: 'bar' }, json: true, callback: [Function: RP$callback], transform: undefined, simple: true, resolveWithFullResponse: false, transform2xxOnly: false }, response: IncomingMessage { _readableState: ReadableState { objectMode: false, highWaterMark: 16384, buffer: [Object], length: 0, pipes: null, pipesCount: 0, flowing: true, ended: true, endEmitted: true, reading: false, sync: true, needReadable: false, emittedReadable: false, readableListening: false, resumeScheduled: false, destroyed: false, defaultEncoding: 'utf8', awaitDrain: 0, readingMore: false, decoder: null, encoding: null }, readable: false, domain: null, _events: { end: [Array], close: [Array], data: [Function], error: [Function] }, _eventsCount: 4, _maxListeners: undefined, socket: Socket { connecting: false, _hadError: false, _handle: null, _parent: null, _host: 'localhost', _readableState: [Object], readable: false, domain: null, _events: [Object], _eventsCount: 8, _maxListeners: undefined, _writableState: [Object], writable: false, allowHalfOpen: false, _bytesDispatched: 175, _sockname: null, _pendingData: null, _pendingEncoding: '', server: null, _server: null, parser: null, _httpMessage: [Object], _idleNext: null, _idlePrev: null, _idleTimeout: -1, [Symbol(asyncId)]: 22, [Symbol(bytesRead)]: 392 }, connection: Socket { connecting: false, _hadError: false, _handle: null, _parent: null, _host: 'localhost', _readableState: [Object], readable: false, domain: null, _events: [Object], _eventsCount: 8, _maxListeners: undefined, _writableState: [Object], writable: false, allowHalfOpen: false, _bytesDispatched: 175, _sockname: null, _pendingData: null, _pendingEncoding: '', server: null, _server: null, parser: null, _httpMessage: [Object], _idleNext: null, _idlePrev: null, _idleTimeout: -1, [Symbol(asyncId)]: 22, [Symbol(bytesRead)]: 392 }, httpVersionMajor: 1, httpVersionMinor: 1, httpVersion: '1.1', complete: true, headers: { 'x-powered-by': 'Express', 'content-security-policy': 'default-src \'self\'', 'x-content-type-options': 'nosniff', 'content-type': 'text/html; charset=utf-8', 'content-length': '148', date: 'Fri, 21 Sep 2018 17:36:52 GMT', connection: 'close' }, rawHeaders: [ 'X-Powered-By', 'Express', 'Content-Security-Policy', 'default-src \'self\'', 'X-Content-Type-Options', 'nosniff', 'Content-Type', 'text/html; charset=utf-8', 'Content-Length', '148', 'Date', 'Fri, 21 Sep 2018 17:36:52 GMT', 'Connection', 'close' ], trailers: {}, rawTrailers: [], upgrade: false, url: '', method: null, statusCode: 404, statusMessage: 'Not Found', client: Socket { connecting: false, _hadError: false, _handle: null, _parent: null, _host: 'localhost', _readableState: [Object], readable: false, domain: null, _events: [Object], _eventsCount: 8, _maxListeners: undefined, _writableState: [Object], writable: false, allowHalfOpen: false, _bytesDispatched: 175, _sockname: null, _pendingData: null, _pendingEncoding: '', server: null, _server: null, parser: null, _httpMessage: [Object], _idleNext: null, _idlePrev: null, _idleTimeout: -1, [Symbol(asyncId)]: 22, [Symbol(bytesRead)]: 392 }, _consuming: true, _dumped: false, req: ClientRequest { domain: null, _events: [Object], _eventsCount: 5, _maxListeners: undefined, output: [], outputEncodings: [], outputCallbacks: [], outputSize: 0, writable: true, _last: true, upgrading: false, chunkedEncoding: false, shouldKeepAlive: false, useChunkedEncodingByDefault: true, sendDate: false, _removedConnection: false, _removedContLen: false, _removedTE: false, _contentLength: null, _hasBody: true, _trailer: '', finished: true, _headerSent: true, socket: [Object], connection: [Object], _header: 'POST /postdata HTTP/1.1\r\nhost: localhost:3000\r\naccept: application/json\r\ncontent-type: application/json\r\ncontent-length: 29\r\nConnection: close\r\n\r\n', _onPendingData: [Function: noopPendingOutput], agent: [Object], socketPath: undefined, timeout: undefined, method: 'POST', path: '/postdata', _ended: true, res: [Circular], aborted: undefined, timeoutCb: null, upgradeOrConnect: false, parser: null, maxHeadersCount: null, [Symbol(outHeadersKey)]: [Object] }, request: Request { domain: null, _events: [Object], _eventsCount: 5, _maxListeners: undefined, method: 'POST', uri: [Object], body: '{"data1":"foo","data2":"bar"}', readable: true, writable: true, explicitMethod: true, _qs: [Object], _auth: [Object], _oauth: [Object], _multipart: [Object], _redirect: [Object], _tunnel: [Object], _rp_resolve: [Function], _rp_reject: [Function], _rp_promise: [Object], _rp_callbackOrig: undefined, callback: [Function], _rp_options: [Object], headers: [Object], setHeader: [Function], hasHeader: [Function], getHeader: [Function], removeHeader: [Function], localAddress: undefined, pool: {}, dests: [], __isRequestRequest: true, _callback: [Function: RP$callback], proxy: null, tunnel: false, setHost: true, originalCookieHeader: undefined, _disableCookies: true, _jar: undefined, port: '3000', host: 'localhost', path: '/postdata', _json: true, httpModule: [Object], agentClass: [Object], agent: [Object], _started: true, href: 'http://localhost:3000/postdata', req: [Object], ntick: true, response: [Circular], originalHost: 'localhost:3000', originalHostHeaderName: 'host', responseContent: [Circular], _destdata: true, _ended: true, _callbackCalled: true }, toJSON: [Function: responseToJSON], caseless: Caseless { dict: [Object] }, read: [Function], body: '\n\n\n\nError\n\n\n
Cannot POST /postdata
\n\n\n' } }

1 answer

  • answered 2018-09-21 18:21 D_________

    your Flask server is listening to port 5000, but your postdatatoFlask method is POSTing to port 3000.

    Change this code:

    var options = {
        method: 'POST',
        uri: 'http://localhost:3000/postdata',
        body: data,
        json: true // Automatically stringifies the body to JSON
    };
    

    to this:

    var options = {
        method: 'POST',
        uri: 'http://localhost:5000/postdata',
        body: data,
        json: true // Automatically stringifies the body to JSON
    };