Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/438.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在服务器上运行javascript实验_Javascript_Node.js_Nodemon - Fatal编程技术网

如何在服务器上运行javascript实验

如何在服务器上运行javascript实验,javascript,node.js,nodemon,Javascript,Node.js,Nodemon,我用JavaScript开发了一个实验,我想在本地主机上运行它。 在粗体行中,我试图发送一个包含实验的HTML文件。这个HTML文件运行良好,当我双击它时,包含我的实验的浏览器打开,实验正在运行。 我还试图发送一个包含我的实验的js文件,但是当我进入我的本地主机时,我只能看到代码,但是代码没有运行。 我正在使用nodemon和jspsych库 //jshing esversion:6 const express = require("express"); const

我用JavaScript开发了一个实验,我想在本地主机上运行它。 在粗体行中,我试图发送一个包含实验的HTML文件。这个HTML文件运行良好,当我双击它时,包含我的实验的浏览器打开,实验正在运行。 我还试图发送一个包含我的实验的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");
})
my 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>

你说在粗体行中,我试图发送一个包含实验的HTML文件。这个HTML文件运行良好,当我双击它时,包含我的实验的浏览器打开,实验正在运行

然而,代码中的粗线条是

res.sendFile\uuu dirname+/exp.js

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


尝试使用express查找如何创建静态web服务器尝试从您的服务器发送.html文件,并告诉您的服务器从何处读取静态文件

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

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

请访问,采取的,看看什么和。做一些研究,搜索相关话题等;如果遇到问题,请发布您的尝试,并使用[]代码段编辑器记录输入和预期输出。将代码发布到我搜索了相关主题,但找不到真正解决问题的主题,我发布了相关代码。请尝试从服务器发送HTML文件。app.use'/',function req,res{res.sendFile'YOUR HTML FILE.HTML';};我的意思是,在粗体行中,我没有发送exp.js,而是发送了index.html和index.html,它们包含在包含我的实验的主体脚本标记中。如果我双击index.html,运行我的实验的浏览器将打开。@achikam您是否在服务器端将mime类型设置为text/html?我当前正在本地主机上运行此操作,是否需要进行任何更改?如果是的话,我在哪里可以准确地更改它们?我看到了在真正的服务器(而不是本地主机)上更改/添加MIME类型的引用@bluejayke@achikam在res.sendFile引用之前使用res.setcontent-type,text/html如果您想对大多数扩展名执行此操作,请在此处复制JSON,但仍然得到相同的结果,localhost包含一个带有我在html文件中设置的主体颜色的空html文件,实验没有运行。听起来不错,从未尝试过这样发送。希望它能起作用我试着写你的代码,并在几个地方将它修改为我的html文件名,比如在我的函数应用程序中。获取或删除这个函数并在同一个地方写你的代码,我仍然得到相同的结果,当我输入localhost:3000时,我可以看到一个带有我在html代码中设置的html主体颜色的空页面。无法看到双击index.html时看到的实际页面