node.js web服务器请求文件未加载

node.js web请求文件无法加载
外置js文件和css无法加载问题

直接使用request.url返回的的是绝对路径
比如http://127.0.0.1:8080/index.html 获取返回的是/index.html
而/index.html是绝对路径,直接定位到根目录找不到文件
改为相对路径可以解决
有两种方法

  1. 第一种
    使用request.url.substr(1)
    把字符串第二个字符后面的字符提取出来
    输出index.html

  2. 第二种
    加一个.
    '.'+request.url
    输出./index.html

let fs=require('fs');
let url=require('url');

let fs1=fs.readFileSync('17index.html');
//console.log(String(fs1));

http.createServer(function(request,response){
    //console.log(String(url.parse.pathname));
    //console.log(typeof request.url);
    //console.log('.'+url.parse(request.url).pathname);
    //console.log(String(fs.readFileSync('.'+request.url)));
    response.write(String(fs.readFileSync(request.url.substr(1))));
    response.end();
}).listen(8080);
posted @ 2022-02-22 13:30  qiwen17  阅读(127)  评论(0)    收藏  举报