我有以下NODEjs POST函数,它向运行python脚本的localhost端口发送请求:
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();
}
这是python脚本中的路由(不是由我编码):
@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)
这是我使用httpPost的请求:
var headers = {
"Content-Type": "application/json"
}
var body = {
"parameter":parameter
}
ut.httpPost(function(response){
callback(response);
},host_endpoint,"/search",headers,body,5000);
1。请求在python进程中收到
2。如果我删除json内容类型,我会收到通知"正文必须是JSON",所以这不是问题。
第3。这个常规请求发出400响应。没有进一步的信息:
<!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>
在python实例中:
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 -
那么,我到底错过了什么? Tyvm
同样, python脚本完全由cURL请求完成。它只是使用节点失败。这是doSearch
python函数:
def doSearch(url):
returned_code = StringIO()
full_url = SEARCH_URL + url
if app.debug:
print 'POST: ' + url
conn = pycurl.Curl()
conn.setopt(conn.URL, str(full_url))
conn.setopt(conn.FOLLOWLOCATION, 1)
conn.setopt(conn.USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11')
conn.setopt(conn.WRITEFUNCTION, returned_code.write)
conn.perform()
conn.close()
return returned_code.getvalue()
最后一次, python脚本完全工作如果我使用终端POST到localhost:5000(python实例正在运行)。它只在请求来自node.js函数时失败。