Browse Source

implement receive json body with cors example file

makefile
Markus Bergholz 4 years ago
parent
commit
0d1d9cde4f
2 changed files with 43 additions and 8 deletions
  1. 30
    0
      json_example.html
  2. 13
    8
      turbowebdis.lua

+ 30
- 0
json_example.html View File

@@ -0,0 +1,30 @@
<html>
<head>
<meta content='text/html; charset=utf-8' http-equiv='content-type'>
<title>turbowebdis</title>
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js'></script>
<script type='text/javascript'>
$(document).ready(function()
{
$('button').on('click', function()
{
$.ajax({
'type' : 'POST',
'dataType' : 'JSON',
'contentType' : 'application/json',
'url' : 'http://localhost:8888/',
'data' : JSON.stringify({"auth": "foobar", "db": 1, "command": ["SET", "SOME", "VALUE"]}),
'success' : function(response)
{
console.log(response);
document.write(JSON.stringify(response));
}
});
})
});
</script>
</head>
<body>
<button>make request</button>
</body>
</html>

+ 13
- 8
turbowebdis.lua View File

@@ -25,7 +25,7 @@ local function callRedis(string)
-- execute command
local unpack = table.unpack
if #auth > 0 then client:call("AUTH", auth) end
if db ~= 0 then client:call("SELECT", db) end
if db ~= "0" then client:call("SELECT", db) end
local value = client:call(unpack(args))
local ret = {}
@@ -37,13 +37,18 @@ end -- function callRedis

local IndexHandler = class("IndexHandler", turbo.web.RequestHandler)

-- Method POST not implemented yet
-- This is needed for e.g. authentification
--function IndexHandler:post()
-- self:add_header('Access-Control-Allow-Origin','*')
-- local json = self:get_json(true)
-- for key,value in pairs(json) do print(key,value) end -- output in terminal!
-- end -- POST
-- Method POST
-- Sending json like this JSON.stringify({"auth": "", "db": 1, "command": ["GET", "SOME", "VALUE"]})
function IndexHandler:post()
self:add_header('Access-Control-Allow-Origin','*')
local json = self:get_json(true)

auth = json['auth'] or auth
db = tostring(json['db'] or db) -- make sure that the db number is a string
local cmd = json['command']

self:write(callRedis(table.concat(cmd,'/')))
end -- POST
-- Method GET
function IndexHandler:get(input)

Loading…
Cancel
Save