简体   繁体   English

NodeJS服务器上的Response.write()或.toString()(错误?)

[英]Response.write() or .toString() (bug?) on NodeJS server

I am a trying to make a small web server for testing. 我正在尝试制作一个小型Web服务器进行测试。 I made it with NodeJS. 我用NodeJS制作的。 But something unexpected happened. 但是出乎意料的事情发生了。 The webpage passed by the NodeJS server couldn't be displayed properly. 由NodeJS服务器传递的网页无法正确显示。 But the webpage worked perfectly when I used php+Apache. 但是当我使用php + Apache时,该网页运行完美。 When I opened the source code received at my client side, there are no observable difference. 当我打开在客户端收到的源代码时,没有明显的区别。 Here is my code: 这是我的代码:

Server.js Server.js

var http = require('http');
var fs = require('fs');
var url = require('url');
var Max = 30;
var port = process.argv[2];

var server = http.createServer( function (request, response) {
    var pathname = url.parse(request.url).pathname; if (pathname == "") pathname = "index.html";
    console.log("Request for " + pathname + " received.");
    fs.readFile(pathname.substr(1), function (err, data) {
            if (err) {
                    console.log(err);
                    response.writeHead(404, {'Content-Type': 'text/html'});
            } else {
                    response.writeHead(200, {'Content-Type': 'text/html'});
                    response.write(data.toString());
            }
            response.end();
    });
}).listen(port);

console.log('Server running at http://127.0.0.1:8081/');


var sockets = {}, nextSocketId = 0;
server.on('connection', function (socket) {
    var socketId = nextSocketId++;
    sockets[socketId] = socket;
    console.log('socket', socketId, 'opened');

    socket.on('close', function () {
            console.log('socket', socketId, 'closed');
            delete sockets[socketId];
    });

    socket.setTimeout(4000);
});

function anyOpen(array) {
    for (var ele in array) {
            if (ele) return true;
    }
    return false;
}


(function countDown (counter) {
    console.log(counter);
    if (anyOpen(sockets)) {
            return setTimeout(countDown, 1000, Max);
    } else if (counter > 0 ) {
            return setTimeout(countDown, 1000, counter - 1);
    };
    server.close(function () { console.log('Server closed!'); });
    for (var socketId in sockets) {
            console.log('socket', socketId, 'destroyed');
            sockets[socketId].destroy();
    }
})(Max);

Chatroom2-0.php Chatroom2-0.php

<!DOCTYPE html> 
<html>
<head>
<style>
    textarea {
            width:95%;
            rows:50;
            height:80%;
    }
</style>
<script     src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">    </script>
<script type="text/javascript">

    var str = "";
    function enter(e){
            if (e.keyCode == 13 && document.getElementById("Input").value) {
                    //alert("Enter!!!!");
                    sendInput();
                    document.getElementById("Input").value = "";
            }
    };

    function updateBoard() {
            xmlhttp = new XMLHttpRequest();

            xmlhttp.onreadystatechange = function() {
                    if ( xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                            document.getElementById("MsgBoard").innerHTML = xmlhttp.responseText;
                    }
                    var textarea = document.getElementById('Output');
                    textarea.scrollTop = textarea.scrollHeight;  
            };

            xmlhttp.open("POST","Server.php",true);
            xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                xmlhttp.send("Type=Username&Content="+document.getElementById("Username").value);
    };

    function sendInput() {
            username = document.getElementById("Username").value; if (!username) username = "Gotemptyname";
            msg = document.getElementById("Input").value; if (!msg) msg = "GotNothing";
            if (msg) {
                    xmlhttp = new XMLHttpRequest();
                    xmlhttp.open("POST","Server.php",true);
                    //xmlhttp.open("POST","test.txt",true);
                    //xmlhttp.send();
                    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");                  
                    xmlhttp.send("Type=Message&Username="+username+"&Content="+msg);
                    //alert(xmlhttp.responseText);
            }
    };

</script>
</head>
<body onload="setInterval('updateBoard()',1000)">
<div id="MsgBoard"></div>
<form name="UsrInput">
<?php
    if (isset($_POST["Username"]))
            echo '<input type="text" id ="Username" value="'.$_POST["Username"].'" disable>';
    else {
            header("Location: /login/index.html");
            die();
    }
?>
<input type="text" id="Input" onkeypress="enter(event)"  value="" >
</form>
</body>
</html> 

Users should be able to access the Chatroom2-0.php after login. 登录后,用户应该可以访问Chatroom2-0.php。 The login functionality is also ok. 登录功能也可以。 But when I entered the Chatroom2-0.php, I got a String, next to my textbox. 但是,当我进入Chatroom2-0.php时,在文本框旁边有一个字符串。

'; '; else { header("Location: /login/index.html"); else {header(“ Location:/login/index.html”); die(); 死(); } ?> }?>

I noticed that the string is part of my php code in the file. 我注意到该字符串是文件中我的php代码的一部分。 I don't know what's happening. 我不知道发生了什么 I think this might have something to do with the response.write() or the data.toString() function. 我认为这可能与response.write()或data.toString()函数有关。 Maybe the function changed something in my coding? 也许函数在我的编码中做了些改变? How could I solve this problem. 我该如何解决这个问题。

Anyway, I appreciate for any help given. 无论如何,我感谢您给予的任何帮助。

The problem is that you are trying to run php code on a nodejs server. 问题是您正在尝试在nodejs服务器上运行php代码。 There is no solution to this, as node is not a php interpreter, so it sees everything as html text; 没有解决方案,因为node不是php解释器,所以它将所有内容视为html文本; thus your php code appearing on the page. 因此,您的php代码出现在页面上。 You need to create an entirely different html for the node project. 您需要为节点项目创建完全不同的html。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM