So I am using express and am trying to run a POST command code :
HTML and JS Code:
<body>
<h1>this is the survey page</h1>
<a href="/api/users">USERS</a>
<form method="POST" role="form">
<input id="name" placeholder="name">
<input id="pic" placeholder="pic">
<button id="submit" type="submit">Submit</button>
</form>
</body>
<script type="text/javascript">
$("#submit").on("click", function(event){
event.preventDefault();
// event.preventDefault();
var newUser = {
name: $("#name").val().trim(),
profile_pic: $("#pic").val().trim(),
scores: [
5,
1,
4,
4,
5,
1,
2,
5,
4,
1
]
}
$.post("/api/users", newUser,
function(data){
if(data){
console.log("you completed the survey")
}
else{
console.log("error");
}
}
);
})
Express Code :
SERVER:
var express = require("express");
var app = express();
var PORT = process.env.PORT || 8080;
// app.use(express.static(__dirname + '/public'));
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
require("./routing/apiRoutes")(app);
require("./routing/htmlRoutes")(app);
app.listen(PORT, function() {
console.log("App listening on PORT: " + PORT);
});
apiRoutes
var userData = require("../data/friends");
module.exports = function(app) {
app.get("/api/users", function(req, res){
res.json(userData);
});
app.post("/api/users"), function(req, res){
userData.push(req.body);
res.json(true);
}
}
HTML ROUTES
var path = require("path");
module.exports = function(app){
app.get("/survey", function(req, res){
res.sendFile(path.join(__dirname, "../public/survey.html"));
})
app.get("*", function(req, res){
res.sendFile(path.join(__dirname, "../public/home.html"));
})
}
Whenever I run click the submit button it should run the post but I get the following error:
jquery.min.js:2 POST http://localhost:8080/api/users 404 (Not Found)
I'm not really sure how to resole this issue, any thoughts?