簡體   English   中英

無法在 node.js express.js 中運行任何正常的 JavaScript 代碼

[英]Can't run any normal javascript code in node.js express.js

我正在學習 express.js,我在這里有這個基本的 express 代碼:

const express = require("express");
const bodyParser = require("body-parser");

const app = express();
const port = 3000;

app.use(bodyParser.urlencoded({ extended: true }))

app.get("/", (req, res) => {
    res.sendFile(__dirname + "/index.html")
})

app.post("/", (req, res) => {
    let n1 = req.body.num1 //num1 and num2 are coming from index.html which I have inciude above
    let n2 = req.body.num2

    let result = n1 + n2
    res.send(result)
})
app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

但它需要 n1 和 n2 作為字符串。 所以如果我給 n1 = 2 和 n2 = 4 它返回 24 但不是 6 所以我嘗試將 n1 和 n2 轉換為數字所以我嘗試過

    let n1 = Number(req.body.num1)
    let n2 = Number(req.body.num2)

但它給出了錯誤,稱為:

RangeError [ERR_HTTP_INVALID_STATUS_CODE]: Invalid status code: 5
at new NodeError (node:internal/errors:372:5)
at ServerResponse.writeHead (node:_http_server:275:11)
at ServerResponse._implicitHeader (node:_http_server:266:8)
at write_ (node:_http_outgoing:766:9)
at ServerResponse.end (node:_http_outgoing:855:5)
at ServerResponse.send (C:\Users\USERNAME \OneDrive\Desktop\lll\calculator\node_modules\express\lib\response.js:232:10)
at ServerResponse.sendStatus (C:\Users\USERNAME \OneDrive\Desktop\\calculator\node_modules\express\lib\response.js:375:15)
at C:\Users\USERNAME \OneDrive\Desktop\lll\calculator\calculator.js:18:9
at Layer.handle [as handle_request] (C:\Users\USERNAME \OneDrive\Desktop\lll\calculator\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\USERNAME \OneDrive\Desktop\lll\calculator\node_modules\express\lib\router\route.js:144:13)

即使我嘗試控制台記錄result類型,它也會返回這種類型的錯誤。 有人能幫助我嗎

index.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>Caluculator</title>
</head>
<body>
    <h1>Caluculator</h1>
    <form action="/" method="post">
    <input type="text" name="num1" placeholder="Enter First Number" />
    <input type="text" name="num2" placeholder="Enter Second Number" />
    <button type="submit" name="submit">Calculate</button>
    </form>
</body>
</html>

錯誤來自這一行 res.sendStatus(result) 結果不是有效的狀態代碼。 代替

let n1 = Number(req.body.num1);

const n1 = +req.body.num1;
const n2 = +req.body.num2;
const result= n1+n2;
res.status(200).send({result, 
message:"success"});

狀態碼必須在 100 到 599 之間

該錯誤確實來自res.sendStatus(result)而應該是res.send(result) 如果您確實想手動設置狀態,那么它應該是res.status(200).send(result) ,將 200 交換為您要設置的狀態碼。

除此之外,您還應該將數字轉換為字符串。 最高效的方法是有爭議的,但我通常這樣做的方法是${n1 + n2}

在您的情況下,通過上述更改,您的 JavScript 應如下所示:

const express = require("express");
const bodyParser = require("body-parser");

const app = express();
const port = 3000;

app.use(bodyParser.urlencoded({ extended: true }))

app.get("/", (req, res) => {
    res.sendFile(__dirname + "/index.html")
})

app.post("/", (req, res) => {
    let n1 = req.body.num1 //num1 and num2 are coming from index.html which I have inciude above
    let n2 = req.body.num2

    let result = n1 + n2
    res.send(`${result}`)
})
app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

Express 文檔中有更多信息。

我找到了這樣的答案Unable to send numbers using res.send() using express with node

您必須發送字符串而不是數字

 app.post("/", (req, res) => { let n1 = Number(req.body.num1) //num1 and num2 are coming from index.html which I have inciude above let n2 = Number(req.body.num2) let result = n1 + n2 res.send(''+result) })

我測試並運行

let n1 = parseInt(req.body.num1);  
let n2 = parseInt(req.body.num2);  
let result = n1 + n2;  
return res.status(200).send({result});  

使用parseInt()后,您將獲得一個整數值。
此外,您可以在變量前使用+號。

 let num1 = "2"; let num2 = "4"; let n1 = parseInt(num1); let n2 = parseInt(num2); let result = n1 + n2; console.log('result >>>', result);

答案是 :

let n1 = req.body.num1
let n2 = req.body.num2
let result = Number(n1) + Number(n2)
res.send("" + result)

您只需添加一個空字符串。 我不知道為什么它有效,但它有效

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM