Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
217 views
in Technique[技术] by (71.8m points)

node.js - Couls someone explain why i get this error? "TypeError: Cannot read property 'split' of undefined"

I'm new to Node js and i have a function that receives a json object with numeric values, that i try to add up and display the result on the browser using a "Sum" property. The problem occurs at the mathsServer.js (split() method in the addera()). I do not understand why i suddenly get this error especially when i modified my code according to a MVC. When i run it independently in one file it worked well at some point. Here is my code. Im supposed to POST a json in postman:

{
"tal": "10,343,24,345,22,23,233, 45, 200,500" }

router.js:

 const express = require("express");
    const router = express.Router();
    const controller = require("./controllers/controller");
    
    router.post("/add", controller.renderSum)
    
    router.get("/add",controller.renderSum)
    
    
    module.exports = router

controller.js:

 const mathServerModel = require("../../../mathServer/model/mathModel");    
    
    exports.renderSum = (req, res) => {  
           
        mathServerModel.addera(req.body.tal)
            .then(function (data) {
                console.log(data);
                //res.send({data});
                res.render("post-tal", {
                    Sum: {data}        // A property called Sum to be displayed on the browser
                })
    
            })
            .catch(error => console.log(error))
        
    }

mathModel.js

const express = require('express');
const bodyParser = require('body-parser'); 
const app = express();

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());


const addera = async (tal) => {
    let strNumbersArr = tal.split(","); // ["10", "343", "24", ..., "233"]
    let sum = 0;
    for(let i = 0; i < strNumbersArr.length; i++) {
        let currentNumberStr = strNumbersArr[i];
        sum += Number(currentNumberStr); // convert current number string into a number
    }
    return sum;
    
}

module.exports = {
    addera
}

index.hbs

<!DOCTYPE html>
<html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>WebApp</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.6.2/css/bulma.min.css">
    <link rel="stylesheet" type="text/css" href="../css/style.css">
    <style>
        .eNavAction {cursor:pointer}
        .buttons {margin-top: 20px}
    </style>
    <script src="js/simple-helper.js"></script>
    <script src="model/customer-model.js"></script>
    <script src="view/customer-view.js"></script>
    <script src="controller/main-controller.js"></script>
   <script>
        
        var Current = {};
        const Model = new TeamsModel();
        const View = new TeamView();
        const ViewTal = new TalView();
        const Controller = new MainController();

        document.addEventListener('DOMContentLoaded', function() {
           // Controller.init();
           Helper.onClassClick('eNavAction',Controller.navAction);
        });

    </script>
</head>
<body>
    <nav class="navbar is-link" role="navigation" aria-label="main navigation">
        <div class="navbar-brand">
            <a class="navbar-item" href="/">
                <span style="font-weight:bold; font-size:20px"  href="http://127.0.0.1:3000/">My Web App</span>
            </a>
        </div>
              
        <div id="navbar" class="navbar-menu">
            <div class="navbar-start">
                <a class="eNavAction navbar-item" action ="teams" href="http://127.0.0.1:3000/">Teams</a>
                <a class="navbar-item" action= "tal">Sum</a>
            </div>
        </div>
    </nav>

    <div class="section">
        <div id="main-container">
            <div class="enterTal">
                <div class="displaySum">
                
                    <p>Sum is: {{Sum}}</p>

                </div>

            </div>     
            
        </div>
    
    </div>
</body>
</html>
question from:https://stackoverflow.com/questions/65623441/couls-someone-explain-why-i-get-this-error-typeerror-cannot-read-property-sp

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It appears in controller.js req.body doesn't have an object tal (req.body.tal). You must start your investigation there. mathServerModel.addera() call is passing Undefined object as parameter.

In mathsServer.js, make your code defensive, by first checking your parameters' validity. Check if they have the values and types you were expecting before going into your function's logic.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...