Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.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
Node.js Js-如何运行不同的页面?_Node.js - Fatal编程技术网

Node.js Js-如何运行不同的页面?

Node.js Js-如何运行不同的页面?,node.js,Node.js,因此,当输入url时:将加载server.js文件(索引文件)。我想在输入url时加载account.js 如何做到这一点?在server.js中,顶部是include account.js> var账户=要求(“./账户”) 在nodejs中的createServer函数中,检查URI是否为/account> //Create Server http.createServer(function (request, response) { // Parse the entire URI

因此,当输入url时:将加载server.js文件(索引文件)。我想在输入url时加载account.js


如何做到这一点?

在server.js中,顶部是include account.js>

var账户=要求(“./账户”)

在nodejs中的createServer函数中,检查URI是否为/account>

//Create Server
http.createServer(function (request, response) {
    // Parse the entire URI to get just the pathname
    var uri = url.parse(request.url).pathname, query;
        if (uri == "/account") //If it's mysite.com/account
        {
            request.setEncoding("utf8");
            request.content = '';
                        //call account.whatever() to route to your account     functionality 
                        //send the response from it

        }
            else if (uri == "/") //It's mysite.com
            {   
                      //call whatever you have in the current server.js
            }
}).listen(8080);

Nodejs是一个守护进程。它不会在您每次发出请求时加载脚本。 您可以使用类似的方法:

var severs = require('server.js'),
    accounts = require('accounts.js');

require('http').createServer(function (req, res) {
    var path = require('url').parse(req.url).pathname;
    res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});

    if (path == '/account') {
        res.end(accounts.run());
    } else {
        res.end(severs.run());
    }
}).listen(80);

最好使用请求路由器-请参阅
connect
express
NPM模块。手动路径比较无法扩展-当您添加越来越多的URL时,它会将代码变成噩梦


对于独立路由器,请参见
clutch
NPM模块,但内部的路由器
connect
更为成熟,可以独立使用
express
connect
的扩展,因此它使用
connect

中的路由器请更新答案,在您回答之前几秒钟我已更改了问题。Nodejs是一个守护进程。它不会在您每次发出请求时加载脚本。run()是一个真正的函数,或者只是为了演示?演示。了解如何在Nodejs中创建模块。