简体   繁体   English

Node.js服务器和PHP服务器的差异与理论混淆

[英]Confusion with theory between the differences of Node.js servers and PHP servers

I have been able to write apps in both node.js and php for a while now, however only really discovered a weird difference that I feel I still do not entirely understand. 我已经能够用node.js和php编写应用程序已有一段时间了,但是我才真正发现了一个奇怪的区别,我觉得我仍然不完全了解。

The difference I think I have noticed is that assuming we have to clients visiting a web app run by php, they will have two completely difference instances of all data on the backend (variables arrays, etc). 我认为我注意到的差异是假设我们必须访问由php运行的Web应用程序的客户端,它们将在后端(变量数组等)上有两个完全不同的所有数据实例。 Where as in node.js, they don't quite. 就像在node.js中一样,它们并不完全相同。

Here is a test I did to try and save some confusion: 这是我为避免混淆而做的测试:

PHP test PHP测试

frontend js 前端js

$.post("/ajax.php", {test:"test"}, function(result){
    console.log(result);
});

ajax.php ajax.php

$testarr = array();

if(isset($_POST['test'])){
    $testarr[] = $_POST['test'];
    print_r($testarr);
}

...In this example, if i visit the app in two different browsers, or even in the same client, the frontend console will always output an array with a single element in it. ...在此示例中,如果我在两个不同的浏览器中甚至在同一客户端中访问该应用程序,则前端控制台将始终输出其中包含单个元素的数组。 So the array essentially resets on refresh obviously/new request. 因此,该阵列本质上会在刷新明显/新请求时重置。

Node.js test Node.js测试

frontend js 前端js

$.post("/test", {test:"test"}, function(result){
    console.log(result);
});

app.js app.js

var testarr = [];
app.post("/test", function(req, res){
    testarr.push(req.body.test);
    console.log(testarr);
});

Here, however, when i refresh the page even from different browsers, the array does not reset and I end up with ["test", "test", "test", etc] on each request. 但是,在这里,即使我从不同的浏览器刷新页面,该数组也不会重置,并且我对每个请求都以[“ test”,“ test”,“ test”等]结束。 How can two different clients from two different browsers access the same array like this? 来自两个不同浏览器的两个不同客户端如何访问这样的同一阵列? usually data has to be shared via a database,special requests, etc right? 通常必须通过数据库,特殊请求等共享数据,对吗?

I am clearly misunderstanding some big philosophy with node.js and I would appreciate anyone with a nice explanation. 我显然误解了node.js的一些大哲学,希望有一个很好的解释的人,我将不胜感激。

区别在于,PHP为每个请求创建了一个新环境,而node.js没有。

我不是最大的PHP专家,但是我认为您可以覆盖PHP数组,而不是添加新元素。您可以使用array_push()将某些内容添加到测试人员中。

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

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