Having some problem getting a client to Post JSON properly, so for diagnostics I came up with the following node.js:
Here's showpost.js:
var express = require('express');
var app = express();
app.use (function(req, res, next) {
var data='';
req.setEncoding('utf8');
req.on('data', function(chunk) {
data += chunk;
});
req.on('end', function() {
req.body = data;
next();
});
});
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
app.post("/peek",function(req,res){
console.log("HEADERS:");
console.log(JSON.stringify(req.headers,null," "));
console.log("BODY:");
console.log(req.body);
res.send(req.headers);
});
app.listen(3001);
console.log('Listening on port 3001');
Here's index.html in the same directory:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<script>
function check(){
var url = "/peek";
var payload = JSON.stringify({"foo":"bar","hoo":["ha","ver"]});
$.ajax({
url: url,
type: "post",
data: payload,
dataType: "json",
contentType:"application/json",
success: function(response) {
$(".out").text(JSON.stringify(response,null," "));
},
error: function(e){
alert(JSON.stringify(e));
}
});
}
</script>
<input type="button" value="peek" onClick="check();">
<pre class="out"></pre>
package.json is something like
{
"name": "peek",
"description": "quick and dirty post peeker",
"version": "0.1.0",
"private": true,
"dependencies": {
"express": "3.x"
}
}
copy these files in a directory, run "npm install" then "nodemon showpost.json" (or plain old "node"). Then localhost:3001/ will have a button to press, or you can post to localhost:3001/peek
No comments:
Post a Comment