I have the following NODEjs POST function that sends a request to a localhost port running a python script:
function httpPost(callback, host, path, headers, body, port){
if(port == undefined){
port = 80;
}
if(headers == undefined){
var headers = {};
}
if(headers['Content-Type'] == undefined)
headers['Content-Type'] = 'application/x-www-form-urlencoded';
var post_options = {
host: host,
path: path,
port: port,
method: 'POST',
headers: headers
};
if(headers['Content-Type'] == "application/json"){
post_options["json"] = true;
}
//either 'querystring' or 'JSON' do not work:
var post_data = JSON.stringify(body);
//var post_data = querystring.stringify(body);
var post_req = http.request(post_options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('Response: ' + chunk);
});
});
// post the data
post_req.write(post_data);
post_req.end();
}
This is the route in the python script (not coded by me):
@app.route('/search', methods = ['POST'])
def search():
if request.headers['Content-Type'] != 'application/json':
return "Requests must be in JSON format. Please make sure the header is 'application/json' and the JSON is valid."
client_json = json.dumps(request.json)
client_data = json.loads(client_json)
code = doSearch(client_data['image_url'])
return parseResults(code)
And this is my request using httpPost:
var headers = {
"Content-Type": "application/json"
}
var body = {
"parameter":parameter
}
ut.httpPost(function(response){
callback(response);
},host_endpoint,"/search",headers,body,5000);
1. The request is received in the python process
2. If I remove the json content type I get the notice "body must be in JSON", so that is not the problem.
3. This regular request hands out a 400 response. No further information:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>The browser (or proxy) sent a request that this server could not understand.</p>
And in the python instance:
Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [16/Mar/2017 16:09:25] "POST /search HTTP/1.1" 400 -
So, what exactly I'm I missing here? Tyvm
via Fane
No comments:
Post a Comment