微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

node js 我的本地主机服务器在“ http://localhost:3000/ ”上无法正常工作,但对于链接{ http://localhost:3000/ index.html } 其工作正常

如何解决node js 我的本地主机服务器在“ http://localhost:3000/ ”上无法正常工作,但对于链接{ http://localhost:3000/ index.html } 其工作正常

node js 我的本地主机服务器在“http://localhost:3000/”上无法正常工作,但是对于链接{ http://localhost:3000/ index.html } 工作正常

        const http = require('http');
        const fs =require('fs');
        const path=require('path');
        
        
        const hostname = 'localhost';
        const port =3000;
        
        const server = http.createServer((req,res) =>{
        
        
            console.log("Request for ' " + req.url +" ' by mehtod "+ req.method);
            
            if(req.method ==='GET'){
                var fileURL;
                if(req.url === '/') {fileURL ='index.html';}
                else{ fileURL = req.url;}
        
                var filePath = path.resolve('./public'+fileURL);
                const fileExt = path.extname(filePath);
                if (fileExt == '.html') {
                  fs.exists(filePath,(exists) => {
                    if (!exists) {
                      res.statusCode = 404;
                      res.setHeader('Content-Type','text/html');
                      res.end('<html><body><h1>Error 404: ' + fileURL + 
                                  ' not found</h1></body></html>');
                      return;
                    }
        
                        res.statusCode=200;
                        res.setHeader('content-Type','text/html');
                        fs.createReadStream(filePath).pipe(res);
        
        
                    })
                }
                else{
                    res.statusCode=404;
                    res.setHeader('content-Type','text/html');
                    res.end('<html><body><h1>Error 404 : '+fileURL + 'not an html file  </h1></body></html>');
                    return;
        
                }
        
        
            } 
              else{
                res.statusCode=404;
                res.setHeader('content-Type','text/html');
                res.end('<html><body><h1>Error 404 : '+req.method + 'not supportive  </h1></body></html>');
                return;
        
        
            }
           
        })
        
        server.listen(port,hostname,()=>{
            console.log(`Server running at http://${hostname}:${port}`);
        })

node js 我的本地主机服务器在“http://localhost:3000/”上无法正常工作,但是对于链接{ http://localhost:3000/ index.html } 工作正常

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。