C.H*_*C.H 2 javascript python json aiohttp
我终于注册了,因为我对我的问题没有更多的想法。我的后端部分使用 asyncio 和 aiohttp,前端部分使用 javascript。但是我遇到了 405 错误。(我确切地说我是这些库的初学者)
我希望从发布请求中检索 json。这里的javascript函数:
function postJson (data){
$.ajax({
url : 'http://localhost:8080/postJson',
type : 'POST',
dataType : 'json',
contentType : 'application/json',
data : data, //data are ready at json format, I do not think I need to use JSON.stringify ? I does not change anything to the error anywhere
success : function(code_html, statut){
console.log("success POST");
},
error : function(resultat, statut, erreur){
console.log("error POST");
}
});
}
Run Code Online (Sandbox Code Playgroud)
和python代码:
async def postJson(request):
data = await request.post()
#some code
return Response()
@asyncio.coroutine
def init(loop):
app = Application(loop=loop)
app.router.add_route('POST', '/postJson', postJson)
handler = app.make_handler()
srv = yield from loop.create_server(handler, '127.0.0.1', 8080)
print("Server started at http://127.0.0.1:8080")
return srv, handler
loop = asyncio.get_event_loop()
srv, handler = loop.run_until_complete(init(loop))
try:
loop.run_forever()
except KeyboardInterrupt:
loop.run_until_complete(handler.finish_connections())
Run Code Online (Sandbox Code Playgroud)
使用此代码,我收到 405 错误。这里有一些关于请求的萤火虫说:
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 // so json is not in the list.
Run Code Online (Sandbox Code Playgroud)
但是,如果我拿回来的线contentType : 'application/json'在我的JavaScript文件,它的工作原理(但请求发送称为对象MultiDictProxy,我不知道如何使用该函数json()从aiohttp.web包(在这里)。
我真的需要得到一个 json 对象。有人可以帮助我吗?
我找到了解决办法。我把结论贴在这里给有兴趣的人:
蟒蛇方面:
更换线app.router.add_route('POST', '/postJson', postConf)通过
app.router.add_route('POST', '/postJson', postConf, expect_handler = aiohttp.web.Request.json)
Run Code Online (Sandbox Code Playgroud)
在 postJson 方法中:
替换data = await request.post()为data = await request.json()
在 javascript 方面:
data : JSON.stringify(data)
Run Code Online (Sandbox Code Playgroud)
有了这个,我的方法有效。