let express=require("express")
let ourApp=express()
ourApp.get('/',function(req,res) {
res.send(
`<form action="/answer" method="POST">
<h1>What is the name of tallest mountain in the world?</h1>
<input name="correct">
<button>Click here to submiit</button> </form>`
) })
ourApp.post('/answer',function(req,res){
if(req.body.correct=="everest")
res.send("Thats a correct answer")
} )
ourApp.listen(3000)
错误:
TypeError: Cannot read property 'correct' of undefined
发布于 2020-09-14 04:46:16
没错,您的应用程序需要一个解析器来解析请求正文。你需要一个中间件程序来解析你的请求体。在安装body-parser之后尝试。
安装后,您可以读取req.body,否则express将无法识别您的req.body对象,
let express = require("express");
let ourApp = express();
var bodyParser = require("body-parser");
ourApp.use(
bodyParser.urlencoded({
extended: true,
})
);
ourApp.use(bodyParser.json());
ourApp.get("/", function (req, res) {
res.send(
`
<form action="/answer" method="POST">
<h1>What is the name of tallest mountain in the world?</h1>
<input name="correct">
<button>Click here to submiit</button> </form>
`
);
});
ourApp.post("/answer", function (req, res) {
if (req.body.correct.toLowerCase() == "everest") return res.send("<h2> Thats a correct answer </h2>");
return res.send("<h2> Nope your are wrong </h2>");
});
ourApp.listen(3000);
试试这段代码。ourApp.use() -在你的应用程序中包含正文解析器中间件,请尝试阅读正文解析器here对你的应用程序做了一些小修改:)
发布于 2020-09-14 04:48:29
原因:- its not working because you need to add some middleware to parse the post data of the body.
ourApp.use(express.json());
ourApp.use(express.urlencoded());
说明如何分析应用程序如何分析POST数据
我的一条建议。
试试这个,这个很管用。
let express=require("express");
let ourApp = express();
ourApp.use(express.json());
ourApp.use(express.urlencoded());
ourApp.get("/", function (req, res) {
res.send(
`<form action="/answer" method="POST">
<h1>What is the name of tallest mountain in the world?</h1>
<input type="text" name="correct" id='jatin'>
<button>Click here to submiit</button> </form> `
);
});
ourApp.post("/answer", function (req, res) {
console.log(req.body);
if (req.body.correct == "everest") res.send("Thats a correct answer");
});
ourApp.listen(3000, function (req, res) {
console.log("server started");
});
https://stackoverflow.com/questions/63877976
复制相似问题