Javascript 尝试将请求作为表单数据发送时显示错误
这是一个简单的计算器,可以添加数字。 html表单将正确加载到浏览器中,但一旦我提交表单,就会得到一个404错误代码 错误代码:Javascript 尝试将请求作为表单数据发送时显示错误,javascript,node.js,express,Javascript,Node.js,Express,这是一个简单的计算器,可以添加数字。 html表单将正确加载到浏览器中,但一旦我提交表单,就会得到一个404错误代码 错误代码:无法发布/index.html index.html: <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Calculat
无法发布/index.html
index.html:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Calculator</title>
</head>
<body>
<h1>Calculator</h1>
<form action="index.html" 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>
//jshint esversion:6
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({extended: true}));
//sending response
app.get("/",function(req, res){
res.sendFile(__dirname + "/index.html");
});
//post
app.post("/",function(req,res){
var num1 = Number(req.body.num1);
var num2 = Number(req.body.num2);
var result = num1 + num2;
res.send("The result is: "+result);
});
//listen to port 3000
app.listen(3000, function(){
console.log("Server listening on port 3000");
});
在express服务器中,您需要对
/
进行post调用,并告诉表单必须将表单数据发送到index.html
这意味着您的表单将向http://localhost:3000/index.html
而不是http://localhost:3000/
您应该将
action=“index.html”
更改为action=“/”
也许操作应该是/
,而不是index.html
。)