JavaScript函数虽然已加载,但未定义

时间:2017-10-15 20:57:15

标签: javascript jquery html http handlebars.js

我正在为JS课程做作业,我遇到了一个奇怪的问题。我已经提出了一个请求'模块'我刚刚在jquery之后开始,然后我加载了必要的js脚本,但是当我尝试在另一个脚本文件中使用请求模块中的函数时,它总是抛出一个未定义的TypeError。奇怪的是,当我在console.log中时,对象就是'没有定义,一切都很好。我似乎无法弄清楚为什么会发生这种情况......我需要一些准则

以下是代码的一部分:

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>SeenIt</title>
    <link rel="stylesheet" href="style/site.css">
    <link rel="stylesheet" href="style/post.css">
    <link rel="stylesheet" href="style/header.css">
    <link rel="stylesheet" href="style/menu.css">
    <link rel="stylesheet" href="style/notifications.css">
    <link rel="stylesheet" href="style/submit.css">
    <link rel="stylesheet" href="style/comments.css">
    <script src="../node_modules/jquery/dist/jquery.min.js"></script>
    <script src="./scripts/request.js"></script>
    <script src="../node_modules/handlebars/dist/handlebars.min.js"></script>
    <script src="./scripts/pageView.js"></script>
    <script src="./scripts/app.js"></script>

</head>
<body>
<div id="container">
</div>
</body>
</html>

我的JS请求模块

let request = (function (){
    const appKey = 'kid_rkR4UTRnb';
    const appSecret = 'd3e9f15502a740fcb1413d7ffe109ab5';
    const baseUrl = 'https://baas.kinvey.com';

    function createAuth(type)
    {
        let authorize = {"Content-Type": "application/json"};
        if(type === 'basic')
        {
            authorize.Authorization = "Basic " + btoa(appKey + ':' + appSecret);
        }
        else if(type === 'kinvey')
        {
            authorize.Authorization = "Kinvey " + localStorage.getItem('authtoken');
        }

        return authorize;
    }

    function makeRequest(destination, endpoint, method, authorization, data)
    {

        let req = {
            url: baseUrl + '/' + destination + '/' + endpoint,
            method: method,
            headers: createAuth(authorization),
        };

        if(data != undefined) req.data = JSON.stringify(data);

        $.ajax(req);
    }

    function register(username, password)
    {
        let data = {
            "username": username,
            "password": password
        };

        return makeRequest('user', appKey, 'POST', 'basic', data);
    }

    function logIn(username, password)
    {
        let data = {
            "username": username,
            "password": password
        };

        return makeRequest('user', appKey + '/login', 'POST', 'basic', data);
    }

    function logout()
    {
        makeRequest('user', appKey + '/_logout', 'POST', 'kinvey');
    }

    return {
         createAuth,
         register,
         logIn,
         logout
    }

})();

主JS应用程序文件

$(() => {
    let main = $('#container');
    initialState();

    $(document).ajaxStart(() => $('#loadingBox').show());
    $(document).ajaxComplete(() => $('#loadingBox').hide());
    $('#infoBox').click(() => $('#infoBox').hide());
    $('#errorBox').click(() => $('#errorBox').hide());

    $(document).on('submit', '#loginForm', login);

    async function viewPage(page)
    {
        if(page == 'home')
        {
            main.html(await loadWelcome(isLoggedIn()));
        }
    }
    // initial functions
    function initialState()
    {
        viewPage('home');
    }
    ///////////////

    // session control
    function login(e)
    {
        e.preventDefault();
        let loginForm = $(this);
        let name = loginForm.find('input[name="username"]').val();
        let password = loginForm.find('input[name="password"]').val();

        request.logIn(name, password) // TYPEERROR UNDEFINED ?!?
        .then(data => {
            request.saveSession(data);
            this.reset();
            viewPage('home');
        })
    }
});

4 个答案:

答案 0 :(得分:1)

请在JS Request Module上尝试return对象,

return {
     createAuth: createAuth,
     register: register,
     logIn: logIn,
     logout: logout
}

答案 1 :(得分:0)

您可以尝试&lt; script&gt;正确加载脚本的属性:

&#13;
&#13;
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>SeenIt</title>
    <link rel="stylesheet" href="style/site.css">
    <link rel="stylesheet" href="style/post.css">
    <link rel="stylesheet" href="style/header.css">
    <link rel="stylesheet" href="style/menu.css">
    <link rel="stylesheet" href="style/notifications.css">
    <link rel="stylesheet" href="style/submit.css">
    <link rel="stylesheet" href="style/comments.css">
    <script src="../node_modules/jquery/dist/jquery.min.js"></script>
    <script src="../node_modules/handlebars/dist/handlebars.min.js"></script>
    <script defer src="./scripts/request.js"></script>
    <script defer src="./scripts/pageView.js"></script>
    <script defer src="./scripts/app.js"></script>

</head>
<body>
<div id="container">
</div>
</body>
</html>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

在你的代码中,函数makeRequest不会返回任何值,因此它将返回undefined。尝试从makeRequest函数返回值。

答案 3 :(得分:0)

当您尝试调用then()方法时崩溃,因为request.logIn()函数返回undefined而不是promise。这可以追溯到makeRequest()函数,它不会返回任何内容,即undefined

makeRequest()函数的最后一行必须是:

return $.ajax(req);