首页 > 解决方案 > 如何在服务器上运行 javascript 实验

问题描述

我用 JavaScript 开发了一个实验,我想在我的本地主机上运行。在粗线中,我尝试发送一个包含实验的 HTML 文件(这个 HTML 文件运行良好,当我双击它时,包含我的实验的浏览器打开并且实验正在运行)。我还尝试向 sendFile 发送一个包含我的实验的 js 文件,但是当我输入我的本地主机时,我只能看到代码,但代码没有运行。我正在使用 nodemon 和库 jspsych。

    //jshing esversion:6

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

const app = express();

// app.use([
//     express.static(__dirname + '/index.html'),
// ]);

// app.use('/', function (req, res) {
//     res.set("content-type", "text/html");
//     res.sendFile(__dirname + '/index.html');
// });

app.get("/", function(req, res){
    res.set("content-type", "text/html");
    res.sendFile(__dirname + "/index.html");
})

app.listen(3000, function(){
    console.log("server started on port 3000");
})

我的 index.html:(我知道我不应该在 html 中编写我的“逻辑”部分,但我需要尽可能简单和快速,至少对于 POC)。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- <script src="jsfiles/jspsych.js" type="text/javascript"></script>
    <script src="jsfiles/plugins/jspsych-html-keyboard-response.js" type="text/javascript"></script>
    <script src="jsfiles/plugins/jspsych-image-keyboard-response.js" type="text/html"></script>
    <link href="jsfiles/css/jspsych.css" rel="stylesheet" type="text/css"> -->

    <script src="jsfiles/jspsych.js" type="text/javascript"></script>
    <script src="jsfiles/plugins/jspsych-html-keyboard-response.js" type="text/javascript"></script>
    <script src="jsfiles/plugins/jspsych-image-keyboard-response.js" type="text/html"></script>
    <link href="public/css/jspsych.css" rel="stylesheet" type="text/css">

    <title>Niv2</title>
</head>
<body style="background-color: rgb(154, 233, 253);">
    <script>
        var random_indexes = [];    //this array will be incahrge of the order of the trials display
        for(var i=0; i<30;i++){     //initialize aray of indexes
            random_indexes[i] = i;
        }
        random_indexes.sort(() => Math.random() - 0.5); //randomize the indexes array
        var blue_prices = [0.9, 0.4, 0.5, 0.3, 0.8, 0.6, 0.5, 0.7, 0.2, 0.7,
         0.4, 0.5, 0.7, 0.3, 0.9, 0.6, 0.1, 0.4, 0.8, 0.2,
         0.1, 0.6, 0.3, 0.5, 0.2, 0.4, 0.8, 0.2, 0.1, 0.3];
        var red_prices = [0.8, 0.2, 0.4, 0.1, 0.6, 0.3, 0.3, 0.5, 0.1, 0.6,
         0.4, 0.5, 0.7, 0.3, 0.9, 0.6, 0.1, 0.4, 0.8, 0.2,
         0.2, 0.9, 0.7, 0.6, 0.3, 0.7, 0.9, 0.5, 0.4, 0.4];
        var blue_result = [];
        var red_result = [];
        var j;
        for(j=0;j<30;j++){      //fillig the array of pictures (nedd to fill it without looping)
            if(j%2==0){
                blue_result[j] = "public/pics/blue1.png>";
                red_result[j] = "public/pics/red1.png>";
            }
            else{
                blue_result[j] = "public/pics/blue2.png>";
                red_result[j] = "public/pics/red2.png>";
            }
        }
        var curr_trial;
        var runner = 0;     //inside the on_finish function, i is not recognized so i have to use runner instead!
        var timeLine = [];
        landing_page = {
            type: "html-keyboard-response",
            stimulus: 
            "<div style='text-align:center; font-size: 1.5rem;'>" +
                "<img src='public/pics/bgu-logo.png' style='max-width:20%;'></img>"+
                "<h3>Study Title: Card selection task</h3>"+
                "<p class='my_italic_p'>Please read this consent form carefully before deciding whether you would like to participate in this study.</p>"+
            "</div>"+
            "<div class='my_div'>"+
                "<h5 class='my_header'>Purpose of the Study:</h5>"+
                "<p class='my_small_p'>Which factors influence how people explore their environment and manifest their preferences towards different stimuli? We hope to learn how quickly<br>and accurately people learn contingencies and how do they affect subsequent decisions.</p>"+
                "<h5 class='my_header'>What you will do in this study:</h5>"+
                "<p class='my_small_p'>You will indicate your preferences towards two presented decks of cards differing in the amount of their associated value and information.<br>You will make responses using a device of your choosing. You will also indicate your comprehension of the task and fill out a few additional questionnaires. </p>"+
                "<h5 class='my_header'>Time Required:</h5>"+
                "<p class='my_small_p'> The study will take approximately 15 minutes to complete.</p>"+
                "<h5 class='my_header'>Risks:</h5>"+
                "<p class='my_small_p'>There are no anticipated risks associated with being in this study.</p>"+
                "<h5 class='my_header'>Benefits:</h5>"+
                "<p class='my_small_p'> At the end of the study, we will provide a thorough explanation of the study and of our hypotheses. There are no foreseeable individual benefits to you as a participant.</p>"+
                "<h5 class='my_header'>Compensation:</h5>"+
                "<p class='my_small_p'> You will receive the amount of pay specified on the sign-up page. Full payment will be given upon indication of successful task completion.</p>"+
                "<h5 class='my_header'>Confidentiality:</h5>"+
                "<p class='my_small_p'>Your participation in this study will remain confidential. Your responses will be assigned a code number, and the list connecting your identity with this number will be kept on a password-protected computer in a locked room, separate from the rest of your data. After the completion of data collection we will destroy the code linking your identity to your data.<br>De-identified data will be kept indefinitely and shared publicly for research purposes, but no identifying information will be shared. Identifiable details, including names, will be retained for 7 years and will be destroyed afterwards, as required by regulations.</p>"+
                "<h5 class='my_header'>Participation and withdrawal:</h5>"+
                "<p class='my_small_p'>Your participation in this study is completely voluntary.  You may skip any questions/tasks you do not want to complete.  You may withdraw at any time without penalty or loss of benefit to which you are otherwise entitled by simply closing the browser window or tab in which you are taking the survey. We encourage you to save this and the following screens via printing or a screenshot to retain our contact information and/or the questions asked..</p>"+
            "</div>"+
            "<p>Press 'y' to continue or 'n' to exit.</p>",
            post_trial_gap: 500,
            choices: ['y', 'n'],
            on_finish: function(data){
                data.location = runner;     //check if neeeded
                if(data.key_press == 89 || data.key_press == 121){  
                    data.displayNext = "<h1 style='color:green;'>The experiment will begin shortly</h1>"; // can add property correct by modify data object directly
                } 
                else if(data.key_press == 78 || data.key_press == 110) {
                    data.displayNext = "<h1 style='color:red;'>You decided NOT to participate in the expiriment</h1>";
                }
            }
        };
        timeLine.push(landing_page);

        jsPsych.data.addProperties({displayNext: 'none'});
        jsPsych.data.addProperties({location: 1});
        jsPsych.data.addProperties({startingTime: 0});
        jsPsych.data.addProperties({selction: 'none'});
        var Total_Payment = 0;

        for(var i=0;i<30;i++){
            var start_time = Date.now();
            curr_trial = {
                type: "html-keyboard-response",
                stimulus: "<div style='text-align:center; font-size: 1.5rem;'> <p>בניסוי זה יופיעו מולך 2 קלפים, בכל שלב עליך לבחור בקלף</p>"+
                        "<p>לכל קלף יש את השווי שלו</p>" +
                    "<p>הסכום שתבחר בכל שלב יצטבר לכדי סכום כולל שאותו תקבל בסוף הניסוי.</p>" +
                    "<div style='width: 700px; padding-left:8%;'>"+
                    "<div style='float: left;'><img src='public/pics/blue_card.png'></img>" +
                    "<p class='small'> <p>for blue card: " + blue_prices[random_indexes[i]] + "</p> <strong>Press the 1 key</strong></p></div>" +
                    "<div class='float: right;'><img src='public/pics/red_card.png'></img>" +
                    "<p class='small'> <p>for red card: "+ red_prices[random_indexes[i]] +"</p> <strong>Press the 2 key</strong></p></div>   </div>" +
                    "</div>",
                post_trial_gap: 500,
                choices: ['1', '2'],

                on_finish: function(data){
                    // alert(startingTime);
                    var timming = (Date.now() - data.startingTime - start_time) / 1000;     //time this trial took in seconds!
                    alert(timming);
                    data.location = runner;
                    if(data.key_press == 49){  
                        //jsPsych.data.addProperties({displayNext: "<img src =" + blue_result[data.location%30]+ " </img>"});
                        data.displayNext = "<img src=" + blue_result[random_indexes[runner]] + " </img> <p>Press any key to continue</p>";
                        data.selction = 'blue';
                        Total_Payment += blue_prices[random_indexes[runner]];
                    } 
                    else if(data.key_press == 50) {
                        data.displayNext = "<img src=" + red_result[random_indexes[runner]] + " </img> <p>Press any key to continue</p>";
                        data.selction = 'red';
                        Total_Payment += red_prices[random_indexes[runner]];
                    }
                    runner = runner + 1;
                }
            };
            timeLine.push(curr_trial);
            var curr_result = {
                type: 'html-keyboard-response',
                stimulus: function(){
                    return jsPsych.data.get().last(1).values()[0].displayNext;
                }
            };

            timeLine.push(curr_result);
        }
        jsPsych.init({
            timeline: timeLine,
            on_data_update: function(data){data.startingTime = Date.now();},
            on_finish: function(){
                jsPsych.data.displayData();}
        });
        
    </script>   
    
</body>
</html>

标签: javascriptnode.jsnodemon

解决方案


您说“在粗体行中,我尝试发送包含实验的 HTML 文件(此 HTML 文件运行良好,当我双击它时,包含我的实验的浏览器已打开并且实验正在运行)。”

然而,您的代码中的粗体线是

res.sendFile(__dirname + "/exp.js")

哪个似乎只发送 JS 文件?您可能希望提供一个扩展名为 .html 的文件作为索引,并在其旁边包含其他 JavaScript 文件

尝试查找如何使用 express 制作静态 Web 服务器


推荐阅读