Implementing simple upvote downvote program
<p>I am using express.js and jQuery to create a basic upvote downvote program. Basically the voting buttons increment/decrement by one whenever pressed and the result of each button click is displayed below. Nothing happens when the buttons are clicked, not even a <code>Cannot POST /</code>. I am not sure what is causing the error. This is what my <code>main.js</code> file looks like:</p><pre><br /><code>$(document).ready(function(){<br />$("#up").click(function(){<br /> var up = $.post("/upvote", {changeBy: 1}, function(dataBack){<br /><br /> $("#upvote").text(dataBack);<br /> });<br /><br />});<br />$("#down").click(function(){<br /> var down = $.post("/downvote", {changeBy: 1},<br /> function(dataBack){<br /> $("#downvote").text(dataBack);<br /> });<br /><br /> });<br />});<br /></code><br /></pre><p>and then on the server side <code>server.js</code>, I have this:</p><pre><br /><code>var express = require("express");<br />var app = express();<br />var bodyParser = require("body-parser");<br />app.use(bodyParser.urlencoded({extended: true}));<br />app.use(express.static("public"));<br /><br />var inc = 0;<br />var dec = 0;<br /><br />app.post("/upvote", function(req, res){<br /> res.setHeader("Content-Type", "application/json");<br /> inc += parseFloat(req.body.changeBy);<br /> res.write(JSON.stringify(inc));<br /> res.end();<br /><br />});<br />app.post("/downvote", function(req, res){<br /> res.setHeader("Content-Type", "application/json");<br /> dec -= parseFloat(req.body.changeBy);<br /> res.write(JSON.stringify(dec));<br /> res.end();<br /><br /> });<br /><br /><br />var server = app.listen(8081, function () {<br /><br /> var host = server.address().address<br /> var port = server.address().port<br /><br /> console.log("Example app listening at http://%s:%s", host, port)<br /><br />})<br /></code><br /></pre><p>A bit of HTML:</p><pre><br /><code><div class="buttons"><br /><button id="down">Downvote</button><br /> <p id="downvote"></p><br /><button id="up">Upvote</button><br /> <p id="upvote"></p><br /></div><br /></code><br /></pre><br /><h2>Click here view more answers <a href="http://ift.tt/1oEijvv">http://ift.tt/1oEijvv</a></h2>
Nhận xét
Đăng nhận xét