我是一名PHP开发人员,最近使用了一些带有Express的node JS。
我感到困惑的一件事是,您如何告诉您的express服务器,一个javascript文件是应该在服务器上执行,还是应该发送到浏览器在客户端执行。
在PHP中,这不是一个问题,因为每个文件类型(PHP,pearl,jpg,js)都有一个专用的运行位置(服务器或客户机)。使用其他语言(如Java和C#)编程的HTTP应用程序也是如此
请考虑以下示例代码
var express=require('express');var app=express();
app.get('/some_page',function(req,res){res.send('hello world');});
App.Listence(3000);
没有涉及JS,所以'hello world'被发送到浏览器,并由浏览器呈现。
但如果密码是
var express=require('express');var app=express();
app.get('/',function(req,res){res.send('console.log('hello world')');});
App.Listence(3000);
这一次我们有了JS函数console.log(),那么Node.JS如何知道if是否应该运行这段代码或将其发送到浏览器。
这是app.get('/',function(req,res){
和}
标记的全部内容
res.send('console.log("hello world!")')
将在客户端页面上打印console.log(“Hello World!”)
res.send('<html><body><script>console.log("hello world!");</script></body></html>')
将在客户端控制台中打印Hello World!
res.send('hello world!');
console.log("hello world!");
将在客户端页面和服务器控制台上打印Hello World!
。
所以基本上所有发送到客户端的代码都将在客户端完成,而没有发送到客户端的代码将在服务器端完成
编辑
就像Ankur Rana说的,你也可以发送Html文件
res.sendFile('index.html');
在与该文件相同的目录中,我们有一个名为index.html的文件:
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div id="myId">console.log("hello world!")</div>
<script>
//regular js here
$("#myId").html("Hello World!");
</script>
</body>
</html>
您使用的是Express
,因此应该使用Statice
中间件显式指定客户端Javascript代码。
在下面的示例中,您定义了public
目录来存储它。
// GET /style.css etc
app.use(express.static(__dirname + '/public'));
其他一切都将在服务器端执行。
有关中间件的更多信息:http://expressjs.com/en/guide/using-middleware.html
将javascript代码放在HTML文件的script标记中,并使用res.sendfile('pathtoFile.HTML')发送它