Been using mongoDB with the mongoose ODM and I can't seem to figure it out. I've been following a tutorial online, but when I test out my code, it gets redirected to an empty page that says "Cannot POST /"
Here is my code:
server.js
var mongoose = require("mongoose");
var bodyParser = require("body-parser");
var express = require("express");
var app = express();
var PORT = 3332;
app.use("/", express.static(__dirname));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost/gamedata", {
useNewUrlParser: true
});
var gameSchema = new mongoose.Schema({
nickname: String
});
var User = mongoose.model("User", gameSchema);
app.post("/addname", (req, res) =>{
var playerNickname = new User(req.body);
playerNickname.save()
.then(item => {
console.log("nickname created")
res.send("item saved to database");
})
.catch(err => {
res.status(400).send("unable to save to database");
console.log("error baby!");
});
});
app.listen(PORT, function () {
console.log("server is up and running using port " + PORT)
});
index.html
<html>
<link href="https://fonts.googleapis.com/css?family=Press+Start+2P&display=swap" rel="stylesheet">
<body>
<h1 class="center-align">Create Nickname</h1>
<form method="post" name="/addname">
<input id="pickName" type='text' name='pickName' placeholder='Nickname' required>
<input id='ready' value=" Ready >" type='submit'>
</form>
</body>
<script>
</script>
</html>
What seems to fix it is when i change
app.use("/", express.static(__dirname));
to the following code:
app.use("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
But in my specific case i cannot do this.
Does anyone know of a work around?
You should change your index.html
Insteady of use:
<form method="post" name="/addname">
you should use:
<form method="post" action="/addname">
This should solve your problem.
The Action Attribute
The action attribute defines the action to be performed when the form is submitted.
Usually, the form data is sent to a page on the server when the user clicks on the submit button.
In the example above, the form data is sent to a page on the server called "/addname". This page contains a script that handles the form data:
If the action attribute is omitted, the action is set to the current page.
The attribute "name" is used in input fields, not in the tag. I just found some information here. https://www.w3schools.com/html/html_forms.asp
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.