1
我有一個nginx服務器,我想建立一個服務,接收一個字符串並返回結果。我打算使用Python進行處理,並將CherryPy作爲接口。我測試了CherryPy的一部分,並且知道它正確接收。當我嘗試使用網頁連接到CherryPy服務時,出現CORS錯誤。我怎樣才能讓他們溝通?CherryPy和CORS
這裏的Python代碼:
import cherrypy
import random
import urllib
class DataView(object):
exposed = True
@cherrypy.tools.accept(media='application/json')
def GET(self):
rawData = cherrypy.request.body.read(int(cherrypy.request.headers['Content-Length']))
b = json.loads(rawData)
return json.dumps({'x': 4, 'c': b})
def CORS():
cherrypy.response.headers["Access-Control-Allow-Origin"] = "*"
if __name__ == '__main__':
conf = {
'/': {
'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
'tools.CORS.on': True,
}
}
cherrypy.tools.CORS = cherrypy.Tool('before_handler', CORS)
cherrypy.config.update({'server.socket_port': 3000})
cherrypy.quickstart(DataView(), '', conf)
這裏是我的網頁:
<html lang="en">
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<link href="http://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet">
<script type="text/javascript">
$(document).on('click', "#submitButton", function(){
$.ajax({
type: 'GET',
url: 'http://localhost:3000',
contentType: 'text/plain',
xhrFields: {
// The 'xhrFields' property sets additional fields on the XMLHttpRequest.
// This can be used to set the 'withCredentials' property.
// Set the value to 'true' if you'd like to pass cookies to the server.
// If this is enabled, your server must respond with the header
// 'Access-Control-Allow-Credentials: true'.
withCredentials: false
},
headers: {
},
success: function() {
console.log("Success");
},
error: function() {
console.log("Fail");
}
});
});
</script>
</head>
<body>
<div id="header">
<h2>PDE Grammar Engine</h2>
<form>
Input Sentence:<br>
<input type="text" name="query" id="query"><br>
<input type="submit" id="submitButton" value="Submit">
</form>
</div>
</div id="results">
</div>
</body>
</html>
你見過這個嗎? http://enable-cors.org/server_nginx.html – bpursley
是的,沒有幫助。在這一點上,我無法確定問題來自哪裏。我不知道這是我的服務器配置還是我的javascript。 – user1209675