【问题标题】:How to run javascript experiment on a server如何在服务器上运行 javascript 实验
【发布时间】:2020-11-29 21:24:11
【问题描述】:

我用 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>

【问题讨论】:

  • 请访问help center,使用tour查看内容和How to Ask。做一些研究,搜索关于 SO 的相关主题;如果您遇到困难,请发布您的尝试minimal reproducible example,并使用[&lt;&gt;] sn-p 编辑器记录输入和预期输出。
  • 也发布你的代码
  • 我搜索了一个相关主题,但找不到真正解决我问题的主题,我发布了相关代码。
  • 尝试从您的服务器发送 HTML 文件。 app.use('/', function (req, res) { res.sendFile('YOUR HTML FILE.html'); });

标签: javascript node.js nodemon


【解决方案1】:

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

但代码中的粗线是

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

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

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

【讨论】:

  • 我的意思是,在粗体行中,我没有发送“exp.js”,而是发送了“index.html”,并且 index.html 在其正文脚本标签中包含了我的实验。如果我双击 index.html,运行我的实验的浏览器就会打开。
  • @achikam 您是否在服务器端将 mime 类型设置为“text/html”?
  • 我目前正试图在我的本地主机上运行它,我需要做任何更改吗?如果是这样,我在哪里可以准确地更改它们? (我看到在真实服务器上更改/添加 MIME 类型的参考,而不是本地主机)@bluejayke
  • @achikam 在 res.sendFile 之前使用res.set("content-type", "text/html")(参考stackoverflow.com/a/23759686/2016831)如果您想对大多数扩展执行此操作,请在此处复制 JSON stackoverflow.com/a/61405385/2016831
  • 仍然得到相同的结果,localhost 包含一个空的 html 文件(带有我在 html 文件中设置的 body-color),实验没有运行。
【解决方案2】:

尝试从您的服务器发送 .html 文件并告诉您的服务器他将从哪里获取要读取的静态文件...

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

app.use('/', function (req, res) {
    res.sendFile('YOUR HTML FILE.html');
});

【讨论】:

  • 听起来不错,从未尝试过这样发送。希望它会工作
  • 我试图在几个地方写你的代码(显然修改为我的 html 文件名),比如在我的函数 app.get 中或删除这个函数并将你的代码写在同一个地方,并且我仍然得到相同的结果,当我输入 localhost:3000 时,我可以看到一个空白页面,其中包含我在 html 代码中设置的 html-body 颜色。 (双击“index.html”时看不到实际页面)
猜你喜欢
  • 1970-01-01
  • 2020-03-16
  • 1970-01-01
  • 2016-02-21
  • 2019-11-29
  • 2022-10-09
  • 2013-08-26
  • 1970-01-01
  • 2018-04-11
相关资源
最近更新 更多