You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决使用JavaScript、HTML、Express开发计算器时出现的‘Cannot POST /index.html’错误

解决表单提交时的“Cannot POST /index.html”错误

嘿,我看你在Udemy的Web开发课程里做简易计算器时遇到了表单提交的问题,别着急,咱们很快就能搞定它!

问题根源

你遇到的Cannot POST /index.html错误,核心原因是表单提交的路径和你的Express服务器配置的POST路由不匹配:

  • 你的Node.js代码里,用app.post('/', ...)配置了根路径/的POST请求处理逻辑;
  • 但HTML表单里的action="index.html"会把请求发送到/index.html这个路径,而你的服务器并没有为这个路径设置POST路由,所以就返回了错误。

修复方案

只需要修改HTML表单的action属性,把它改成根路径"/",这样表单提交的请求就会被你已经配置好的app.post('/')路由处理了。

修改后的HTML代码

<!DOCTYPE html> 
<html lang="en"> 
<head> 
  <meta charset="UTF-8"> 
  <meta http-equiv="X-UA-Compatible" content="IE=edge"> 
  <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
  <title>Calculator</title> 
</head> 
<body> 
  <!-- 把action改为根路径"/" -->
  <form action="/" method="post"> 
    <input type="text" name="num1" placeholder="First Number"> 
    <input type="text" name="num2" placeholder="Second Number"> 
    <button type="submit" name="submit">Calculate</button> 
  </form>
</body> 
</html>

Node.js代码无需修改(保持原样即可)

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(req, res) { 
  console.log(req.body); 
  res.send("Thanks for Posting that! "); 
}); 
app.listen(3000, function() { 
  console.log("Server Started on Port 3000"); 
});

验证效果

修改完之后,重启你的Express服务器,再提交表单,就能看到你想要的Thanks for Posting that!提示了,同时终端里也会打印出表单提交的num1和num2数据哦。

内容的提问来源于stack exchange,提问作者user16548463

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 03:57:44