我正在學習 express node.js 并嘗試運行簡單的計算器代碼,但是每當我按下按鈕時,我都沒有得到任何回應,而且我的代碼中也沒有任何錯誤,所以我有點迷失了我做錯了。這是它的示例,因此希望有人能指出我哪里出錯了,包括 html 代碼和calculator.js 以及我遇到的錯誤。先感謝您。
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h1>Calculator</h1>
<form action="/" method="post">
<input type="text" name="n1" placeholder="Enter Number1" value="">
<input type="text" name="n2" placeholder="Enter Number2" value="">
<button type="submit" name="submit">Calculate</button>
</form>
</body>
</html>
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.urlencoded({extended : true}));
app.get("/",function(req,res){
res.sendFile(__dirname "/index.html");
});
app.post("/",function(res,req){
var n1 = Number(req.body.n1);
var n2= Number(req.body.n2);
var result= n1 n2;
res.send("The result of calculation is" result);
});
app.listen(2424,function(){
console.log("Server started on 2424");
});
但這是我點擊計算按鈕后立即收到的錯誤:
TypeError: Cannot read properties of undefined (reading 'n1')
at C:\Users\Taniya\desktop\calculator\calc.js:12:28
at Layer.handle [as handle_request] (C:\Users\Taniya\desktop\calculator\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\Taniya\desktop\calculator\node_modules\express\lib\router\route.js:144:13)
at Route.dispatch (C:\Users\Taniya\desktop\calculator\node_modules\express\lib\router\route.js:114:3)
at Layer.handle [as handle_request] (C:\Users\Taniya\desktop\calculator\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\Taniya\desktop\calculator\node_modules\express\lib\router\index.js:284:15
at Function.process_params (C:\Users\Taniya\desktop\calculator\node_modules\express\lib\router\index.js:346:12)
at next (C:\Users\Taniya\desktop\calculator\node_modules\express\lib\router\index.js:280:10)
at C:\Users\Taniya\desktop\calculator\node_modules\body-parser\lib\read.js:137:5
at AsyncResource.runInAsyncScope (node:async_hooks:203:9)
uj5u.com熱心網友回復:
app.post("/",function(res,req){
您應該將其更改為
app.post("/",function(req,res){
這對我有用!
uj5u.com熱心網友回復:
當您提出請求時,您是否提供了 req.body?看起來是未定義的!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/526317.html
上一篇:為什么graphQL需要端點?應用程式本身就不能擁有一切嗎?
下一篇:從第三列中洗掉前導0
