node.js写的一个五子棋 怎么访问html页面?
发布于 12 年前 作者 justlikeheaven 7325 次浏览 最后一次编辑是 8 年前

我本地也只是在浏览器里这样的地址才能访问页面: file:///D:/node/five/client/ws.html

http://localhost:8080/也只是出来一句话: Welcome to socket.io.

但是怎么访问页面呢?下面的访问方式都不能访问: http://localhost:8080/five/client/ws.html 或者http://localhost:8080/node/five/client/ws.html也不行

请问各位 怎么访问?

6 回复

localhost:8080上跑的是服务器端 这个客户端需要自己再开一个web服务器来运行的 那个包里面没看到服务器端程序 需要自己写一个的

var http = require(‘http’); var fs = require(‘fs’); var path = require(‘path’); var util = require(‘util’);

http.createServer(function (request, response) {

console.log('request starting...');
 
var filePath = '.' + request.url;
if (filePath == './')
    filePath = './ws.html';
     
var extname = path.extname(filePath);
var contentType = 'text/html';
var ifbinary = false;
switch (extname) {
    case '.js':
        contentType = 'text/javascript';
        break;
    case '.css':
        contentType = 'text/css';
        break;
    case '.gif':
        contentType = 'image/gif';
        ifbinary = true;
        break;
    case '.png':
        contentType = 'image/png';
        ifbinary = true;
        break;
    case '.jpg':
        contentType = 'image/jpeg';
        ifbinary = true;
        break;
}
 
path.exists(filePath, function(exists) {
 
    if (exists) {
        if (ifbinary) {
            fs.stat(filePath, function(error, stat) {
                var rs;
                response.writeHead(200,{ 'Content-Type': contentType, 'Content-Length' : stat.size });
                rs = fs.createReadStream(filePath);
                util.pump(rs, response, function(err) {
                    if(err) {
                      throw err;
                    }
                });
            });
        }
        else {
            fs.readFile(filePath, function(error, content) {
                if (error) {
                    response.writeHead(500);
                    response.end();
                }
                else {
                    response.writeHead(200, { 'Content-Type': contentType });
                    response.end(content, 'utf-8');
                }
            });
        }
    }
    else {
        response.writeHead(404);
        response.end();
    }
});

}).listen(8125);

console.log(‘Server running at http://127.0.0.1:8125/’);

我那现成的东西改了一下 用这个来运行客户端 然后就可以用localhost:8125来访问ws.html了

在本地随便架设一个就可以了吧~

楼主能分享下五子棋的源码么?原作者提供的地址连接坏了。我的邮箱是hohai_wow@hotmail.com,不胜感激!!!

您好!按照您的解决方案大部分网页都可以访问了。 但是有参数的网页访问不了,报404错误。 例如:http://127.0.0.1:8125/abc.html?var=3 自我感觉这跟filePath变量的相关处理有关,但涉及多出不知道具体应该怎么修改。 新人,请指教!

关于参数的问题,木有人回答,只好自己解决了。 解决方案就是加一个fileName变量,判断字串里是否有’?’。如果有的话就去掉参数。代码如下:

if (filePath.indexOf(’?’)>0) var fileName = filePath.substr(0,filePath.indexOf(’?’)); else var fileName = filePath;

然后以下所有的filePath都替换成fileName。

回到顶部