I'm trying to pass a json object between a server and client. The server-side this far looks like:
var express = require('express'); // Express web server framework
var request = require('request'); // "Request" library
var querystring = require('querystring');
var cookieParser = require('cookie-parser');
var app = express();
app.use(express.static("public"))
app.get("/", function (req, res) {
})
app.get("/callback", function(req, res){
console.log('Request received');
res.writeHead(200, {
'Content-Type': 'text/plain',
'Access-Control-Allow-Origin': '*'
});
req.on('data', function (chunk) {
console.log('GOT DATA!');
});
res.end('{"msg": "OK"}');
})
var server = app.listen("8080")
console.log('Server running port
With the following function attached to a button.
<script type="text/javascript">
document.getElementById("myBtn").addEventListener("click", passArg);
function passArg() {
console.log("I'm here")
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if (xmlhttp.status == 200) {
xmlhttp.open("POST", "localhost:8080")
}
else if (xmlhttp.status == 400) {
alert('There was an error 400');
}
else {
alert('something else other than 200 was returned');
}
}
};
xmlhttp.open("POST", "/callback", true);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8")
xmlhttp.send(JSON.stringify({myname: "somename"}))
}
</script>
Now upon clicking the console log "I'm here" triggers fine, but the function returns a 404 error on the POST part of the code. I also don't entirely understand how to pass data back to the client from the server. Would the method res.end() be the correct way?
via Copperwire
No comments:
Post a Comment