I just started learning Node and Express for a simple project but for some reason I cannot get POST to work. My browser gives me an error: Cannot POST /
Any assistance with this issue is appreciated. Thank you.
My code is below:
let express = require("express")
let ourApp = express()
ourApp.use(express.urlencoded({ extended: false }))
ourApp.get("/", function(req, res) {
res.send(`
<form action='/' method='POST'>
<h2>What color is the sky on a clear and sunny day?</h2>
<input name="skyColor" autocomplete="off">
<button>Submit Answer</button>
</form>
`)
})
ourApp.post("/answer", function(req, res) {
if (req.body.skyColor.toUpperCase() == "BLUE") {
res.send(`
<p>Congrats, that is the correct answer.</p>
<a href="/">Back to homepage</a>
`)
} else {
res.send(`
<p>Sorry, that is incorrect.</p>
<a href="/">Back to homepage</a>
`)
}
})
ourApp.get("/answer", function(req, res) {
res.send("Are you lost there is nothing to see here.")
})
ourApp.listen(3000)
For the "/"
route, the form
you return should have action="/answer"
, not action="/"
Your other routes should stay the same, and pretty sure that should work.
ourApp.get("/", function(req, res) {
res.send(`
<form action='/answer' method='POST'>
<h2>What color is the sky on a clear and sunny day?</h2>
<input name="skyColor" autocomplete="off">
<button>Submit Answer</button>
</form>
`)
})
You are hitting wrong endpoint. You should post to for example http://localhost:3000/answer .
And one more thing if you want to pass JSON data in body you need to use body-parser middleware. https://www.npmjs.com/package/body-parser
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.