Node.js Express计算器POST请求未进入switch case问题求助
Hey there! Let's figure out why your calculator's switch case isn't firing and it's always hitting the default. I've run into similar snags when starting out with Express, so here are the most likely fixes to get your calculator working:
Express doesn't automatically parse URL-encoded form data from POST requests. If you skip this middleware, req.body will be undefined—meaning your switch has no value to match against, so it'll always fall to default. Add this line before your routes in your Express app:
app.use(express.urlencoded({ extended: true }));
This tells Express to unpack the form data so you can access values like req.body.a, req.body.b, and your operation field.
From your HTML snippet, let's say you have an input/select for the operation (like addition, subtraction). For example, if your operation selector looks like this:
<select name="operation"> <option value="add">Add</option> <option value="subtract">Subtract</option> </select>
Your backend code must reference req.body.operation in the switch statement. If the name attribute on your form control doesn't exactly match what you're checking in the switch, it'll never hit the right case.
Your form uses action="calculate", so make sure your Express POST route is defined correctly:
app.post('/calculate', (req, res) => { // Pull values from the form (note: form data comes as strings!) const { a, b, operation } = req.body; const numA = parseFloat(a); const numB = parseFloat(b); let result; switch(operation) { case 'add': result = numA + numB; break; case 'subtract': result = numA - numB; break; case 'multiply': result = numA * numB; break; case 'divide': result = numB !== 0 ? numA / numB : 'Cannot divide by zero'; break; default: result = 'Invalid operation selected'; } // Send the result back (adjust this to match how you want to display it) res.send(`<h3>Result: ${result}</h3>`); });
If your route uses a different path (like /calc instead of /calculate), the request will go nowhere useful—though since you're getting the default result, this is less likely, but still worth confirming.
It's super easy to mix up strings between your form's value attributes and switch cases. For example, if your form uses value="addition" but your switch checks for case 'add':, they won't match. Make sure the strings are identical (capitalization matters too!).
If you share the full backend code and the rest of your HTML form, I can help troubleshoot further!
内容的提问来源于stack exchange,提问作者Devendra Vastrakar

