AngularJS http.post与cherrypy

时间:2014-01-30 18:37:00

标签: javascript angularjs post curl cherrypy

我正在尝试将事件发布到CherryPy小应用程序中,该应用程序响应GET / POST但在使用AngularJS进行尝试时,它根本就不会发布任何内容。

现在,我不知道这是与AngularJS还是与CherryPy(CP)有关,在CP中启用了跨域,但它根本无法获取POST方法。但是这适用于CURL

CP中的POST定义为:

    def POST(self, date, description):
    # read items to catch any server side update
    events = {
        "date": int(date.encode('ascii','ignore')),
        "description": description.encode('ascii','ignore'),
        "status":"Active"
    }
    # storing changes
    save_events(events)
    return ('Event created\n')

通过以下方式启用标头:

def enableCrossDomain():
cherrypy.response.headers["Access-Control-Allow-Origin"] = "*"
cherrypy.response.headers["Access-Control-Allow-Methods"] = "GET, POST"
cherrypy.response.headers["Access-Control-Allow-Headers"] = "Cache-Control, X-Proxy-Authorization, X-Requested-With"

def OPTIONS(self):
    enableCrossDomain()
    return

CURL调用如下所示:

curl -d $EPOCH_DATE -d $EVENT -X POST 'myurl.com:1234/api/events/'

使用AngularJS尝试:

var message = "'" + $scope.event_description + "' '" + $scope.datetime_start + "'";
            console.log(message);
            $scope.post_url = "myurl.com:1234/api/events";
            $http.post($scope.post_url,message).success();

已经尝试将“消息”作为JSON发布并在标题中指定它但却无法使其工作。任何想法我错过了什么或者我应该在这里尝试什么?

1 个答案:

答案 0 :(得分:1)

似乎答案很简单:

网址未正确编码,因此浏览器正在疯狂;改变了这个:

$scope.post_url = "myurl.com:1234/api/events";

有关

$scope.post_url = "http://myurl.com:1234/api/events";

然后只是错误地解析了消息,我注意到以下消息:

HTTPError: (404, 'Missing parameters: message')

为了简单起见,将参数更改为一条消息并在python内部拆分,然后我的整个POST调用更改为:

$scope.post_url = "http://myurl.com:1234/api/events";
var message = 'message=' + $scope.datetime_start + ',' + $scope.event_description;
$http({
    method: 'POST',
    url: $scope.post_url,
    data: message,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});

同样重要的是,在python端我没有将标题附加到POST消息,更改了以下内容:

def POST(self, date, description):
# read items to catch any server side update
events = {
    "date": int(date.encode('ascii','ignore')),
    "description": description.encode('ascii','ignore'),
    "status":"Active"
}
# storing changes
save_events(events)
return ('Event created\n')

为此:

def POST(self, message):
    # read items to catch any server side update
    events = {
        "date": int(message.split(',')[0].encode('ascii','ignore')),
        "description": message.split(',')[1].encode('ascii','ignore'),
        "status":"Active"
    }
    # storing changes
    save_events(events)
    enableCrossDomain() # HEADERS HERE OR AJAX GETS ANGRY
    return ('Event created\n')