3
노드를 사용하여 Flask로 JSON 데이터를 보내려고하지만 Flask에서 데이터를 읽을 수 없습니다. 나는 플라스크에 request.data
인쇄를 시도했지만 아무것도 출력하지 않았다. 또한 request.json
인쇄를 시도했지만 400 응답을 반환했습니다. 왜 Flask는 Node가 보낸 JSON 데이터를 보지 않습니까? 자바 스크립트에서플라스크에 노드에서 보낸 JSON 데이터가 표시되지 않습니다.
from flask import Flask
from flask import request
app = Flask(__name__)
@app.route("/", methods=['GET', 'POST'])
def hello():
if request.method == "POST":
print "POST";
print "get_json: ", request.get_json();
# print "get_json: ", request.get_json(force = True);
print "data: ", request.data;
return 'POST';
else:
print "GET";
return "GET";
if __name__ == "__main__":
app.run()
var async = require('async'),
http = require('http'),
util = require('util');
var server = {
hostname: '127.0.0.1',
port: 5000
};
function request(method, path, headers, body, callback) {
var req = {};
if(!headers) {
headers = {};
}
headers['Content-Type'] = 'application/json';
console.log(method + ' ' + path);
console.log(' Req:');
console.log(' headers: ' + JSON.stringify(headers));
if(body) {
console.log(' body : ' + JSON.stringify(body));
} else {
console.log(' no body');
}
req = http.request({
hostname: server.hostname,
port: server.port,
path: path,
method: method,
headers: headers
}, (res) => {
var resbody = '';
res.on('data', (chunk) => {
resbody = resbody + chunk;
});
res.on('end',() => {
console.log(' Res:');
console.log(' headers: ' + JSON.stringify(res.headers));
if(body) {
console.log(' body : ' + JSON.stringify(resbody));
} else {
console.log(' no body');
}
callback(resbody);
});
}
);
req.on('error', (err) => {
console.log(method + ' ' + path + ' ERR: ' + util.inspect(err));
callback(err);
});
if(body) {
req.write(JSON.stringify(body));
}
req.end();
}
request('POST', '/', null, {foo: 'bar'}, (res) => {});
출력 : 파이썬에서
POST/
Req:
headers: {"Content-Type":"application/json"}
body : {"foo":"bar"}
Res:
headers: {"content-type":"text/html","content-length":"192","server":"Werkzeug/0.11.11 Python/2.7.11","date":"Fri, 09 Sep 2016 10:29:58 GMT"}
body : "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2 Final//EN\">\n<title>400 Bad Request</title>\n<h1>Bad Request</h1>\n<p>The browser (or proxy) sent a request that this server could not understand.</p>\n"
출력 :에
POST
get_json: 127.0.0.1 - - [09/Sep/2016 12:29:58] "POST/HTTP/1.1" 400 -
을 편집 모든 코드 업데이트.
는컬은 :
> curl.exe 127.0.0.1:5000 --header "Content-Type: application/json" --data {\"foo\":\"bar\"}
POST
'에 http : // httpbin.org/post' 당신이 보낸 어떤 반향하는 다시 JSON 응답을 얻을 것; 동일한 결과를 얻을 수 있습니다 (POST 본문에는 아무 것도 보내지 않습니다). –
아, JSONified 본문이 어디에 쓰여 있는지 알 수 있습니다. 그러나 Content-Length 헤더가 설정되지는 않습니다. [node.js'http.request()'문서] (https://nodejs.org/api/http.html#http_http_request_options_callback)를 살펴보면 코드에 헤더를 명시 적으로 설정합니다. –
@ davidism : 동일한 결과, 아무것도 인쇄되지 않으며 노드에 400 오류가 발생합니다. – DrakaSAN