Python Flask Node.js无法加载资源404

时间:2018-09-21 18:00:38

标签: python node.js flask http-status-code-404

嗨,我正在尝试将数据从node发送到python。我读到这可以通过Express和Flask通过2服务器进行。但是,当我运行代码时,我收到一个错误(见下文)

Python脚本

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)

节点脚本

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);

但是,如果我现在尝试使用以下命令执行发布请求 http://localhost:3000/postdatatoFlask我收到404错误

PS C:\ Users \ danie \ Desktop \ nodepythonproject>节点nodepython {StatusCodeError:404-“ \ n \ n \ n \ nError \ n \ n \ n

Cannot POST /postdata
\ n \ n \ n”     在新的StatusCodeError(C:\ Users \ danie \ node_modules \ request-promise-core \ lib \ errors.js:32:15)     在Request.plumbing.callback(C:\ Users \ danie \ node_modules \ request-promise-core \ lib \ plumbing.js:104:33)     在Request.RP $ callback [作为_callback](C:\ Users \ danie \ node_modules \ request-promise-core \ lib \ plumbing.js:46:31)     在Request.self.callback(C:\ Users \ danie \ node_modules \ request \ request.js:185:22)     在emitTwo(events.js:126:13)     在Request.emit(events.js:214:7)     应要求。 (C:\ Users \ danie \ node_modules \ request \ request.js:1157:10)     在emitOne上(events.js:116:13)     在Request.emit(events.js:211:7)     在IncomingMessage。 (C:\ Users \ danie \ node_modules \ request \ request.js:1079:12)     在Object.onceWrapper(events.js:313:30)     在emitNone(events.js:111:20)     在IncomingMessage.emit(events.js:208:7)     在endReadableNT(_stream_visible.js:1064:12)     在_combinedTickCallback(内部/进程/next_tick.js:138:11)     在process._tickCallback(内部/进程/next_tick.js:180:9)   名称:“ StatusCodeError”,   statusCode:404,   消息:“ 404-“ \ n \ n \ n \ n错误\ n \ n \ n
Cannot POST /postdata
\ n \ n \ n”',   错误:“ \ n \ n \ n \ n错误\ n \ n \ n
Cannot POST /postdata
\ n \ n \ n”,   选项:    {方法:“ POST”,      uri:'http://localhost:3000/postdata',      正文:{data1:'foo',data2:'bar'},      json:是的,      回调:[功能:RP $回调],      转换:未定义,      简单:正确,      resolveWithFullResponse:否,      transform2xxOnly:false},   响应:    IncomingMessage {      _可读状态:       ReadableState {         objectMode:否,         highWaterMark:16384,         缓冲区:[对象],         长度:0,         管道:null,         pipeCount:0,         流动:是的,         结束:是的,         endEmitted:是的,         阅读:错误,         同步:是的,         needReadable:否,         标的是:         可读听:false,         resumeScheduled:否,         销毁:错误,         defaultEncoding:'utf8',         awaitDrain:0,         阅读更多:false,         解码器:null,         编码:null},      可读:错误,      域:null,      _事件:       {end:[Array],         关闭:[Array],         数据:[功能],         错误:[功能]},      _eventsCount:4      _maxListeners:未定义,      插座:       插座{         连接:错误,         _hadError:否,         _handle:null,         _parent:null,         _host:'本地主机',         _可读状态:[对象],         可读:错误,         域:null,         _events:[对象],         _eventsCount:8         _maxListeners:未定义,         _writableState:[Object],         可写:错误,         allowHalfOpen:否,         _bytesDispatched:175,         _sockname:null,         _pendingData:空,         _pendingEncoding:'',         服务器:null,         _server:null,         解析器:null,         _httpMessage:[对象],         _idleNext:空,         _idlePrev:null,         _idleTimeout:-1,         [Symbol(asyncId)]:22,         [Symbol(bytesRead)]:392},      连接:       插座{         连接:错误,         _hadError:否,         _handle:null,         _parent:null,         _host:'本地主机',         _可读状态:[对象],         可读:错误,         域:null,         _events:[对象],         _eventsCount:8         _maxListeners:未定义,         _writableState:[Object],         可写:错误,         allowHalfOpen:否,         _bytesDispatched:175,         _sockname:null,         _pendingData:空,         _pendingEncoding:'',         服务器:null,         _server:null,         解析器:null,         _httpMessage:[对象],         _idleNext:空,         _idlePrev:null,         _idleTimeout:-1,         [Symbol(asyncId)]:22,         [Symbol(bytesRead)]:392},      httpVersionMajor:1      httpVersionMinor:1      httpVersion:“ 1.1”,      完成:正确,      标头:       {'x-powered by':'Express',         'content-security-policy':'default-src \'self \',         'x-content-type-options':'nosniff',         'content-type':'文本/ html; charset = utf-8',         'content-length':'148',         日期:'星期五,2018年9月21日17:36:52 GMT',         连接:“关闭”},      rawHeaders:       ['X-Powered-By',         '表达',         “内容安全政策”,         'default-src \'self \',         'X-Content-Type-Options',         'nosniff',         '内容类型',         'text / html; charset = utf-8',         “内容长度”,         '148',         '日期',         '周五,2018年9月21日17:36:52 GMT',         '连接',         '关' ],      预告片:{},      rawTrailers:[],      升级:错误,      网址:“,      方法:null,      statusCode:404,      statusMessage:“未找到”,      客户:       插座{         连接:错误,         _hadError:否,         _handle:null,         _parent:null,         _host:'本地主机',         _可读状态:[对象],         可读:错误,         域:null,         _events:[对象],         _eventsCount:8         _maxListeners:未定义,         _writableState:[Object],         可写:错误,         allowHalfOpen:否,         _bytesDispatched:175,         _sockname:null,         _pendingData:空,         _pendingEncoding:'',         服务器:null,         _server:null,         解析器:null,         _httpMessage:[对象],         _idleNext:空,         _idlePrev:null,         _idleTimeout:-1,         [Symbol(asyncId)]:22,         [Symbol(bytesRead)]:392},      _using:是的,      _dumped:错误,      要求:       ClientRequest {         域:null,         _events:[对象],         _eventsCount:5         _maxListeners:未定义,         输出:[],         outputEncodings:[],         outputCallbacks:[],         outputSize:0,         可写:是的,         _last:是的,         升级:错误,         chunkedEncoding:否,         shouldKeepAlive:否,         useChunkedEncodingByDefault:true,         sendDate:否,         _removedConnection:否,         _removedContLen:否,         _removedTE:否,         _contentLength:null,         _hasBody:是的,         _预告片: '',         完成:是的,         _headerSent:是的,         套接字:[对象],         连接:[对象],         _header:'POST / postdata HTTP / 1.1 \ r \ nhost:localhost:3000 \ r \ naccept:application / json \ r \ ncontent-type:application / json \ r \ ncontent-length:29 \ r \ n连接:close \ r \ n \ r \ n',         _onPendingData:[功能:noopPendingOutput],         代理:[对象],         socketPath:未定义,         超时:未定义,         方法:“ POST”,         路径:“ / postdata”,         _ended:对,         RES:[通告],         已终止:未定义,         timeoutCb:空,         upgradeOrConnect:否,         解析器:null,         maxHeadersCount:null,         [Symbol(outHeadersKey)]:[Object]},      请求:       请求{         域:null,         _events:[对象],         _eventsCount:5         _maxListeners:未定义,         方法:“ POST”,         uri:[对象],         正文:'{“ data1”:“ foo”,“ data2”:“ bar”}',         可读:正确,         可写:是的,         explicitMethod:正确,         _qs:[对象],         _auth:[对象],         _oauth:[对象],         _multipart:[对象],         _redirect:[对象],         _tunnel:[对象],         _rp_resolve:[功能],         _rp_reject:[功能],         _rp_promise:[对象],         _rp_callbackOrig:未定义,         回调:[功能],         _rp_options:[对象],         标头:[Object],         setHeader:[功能],         hasHeader:[功能],         getHeader:[功能],         removeHeader:[功能],         localAddress:未定义,         池:{},         目的:[],         __isRequestRequest:是的,         _callback:[功能:RP $ callback],         代理:null,         隧道:错误,         setHost:是的,         originalCookieHeader:未定义,         _disableCookies:是的,         _jar:未定义,         端口:“ 3000”,         主机:“ localhost”,         路径:“ / postdata”,         _json:是的,         httpModule:[对象],         agentClass:[Object],         代理:[对象],         _started:是的,         href:“ http://localhost:3000/postdata”,         要求:[对象],         ntick:是的,         回应:[通告],         originalHost:'localhost:3000',         originalHostHeaderName:'主机',         responseContent:[通告],         _destdata:是的,         _ended:对,         _callbackCalled:true},      toJSON:[功能:responseToJSON],      无用的:无用的{dict:[Object]},      读取:[功能],      正文:'\ n \ n \ n \ nError \ n \ n \ n
Cannot POST /postdata
\ n \ n \ n'}}

1 个答案:

答案 0 :(得分:1)

您的Flask服务器正在侦听端口5000,但是您的postdatatoFlask方法正在POST到端口3000。

更改此代码:

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

对此:

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