有关write after end 的问题 ,有懂哥吗


const http = require('http');
const url = require('url');
const path = require('path');
const routes = require('./module/routes');

http.createServer(function (req, res) {
    //创建静态web服务
    var flag=false
   flag= routes.static(req, res, 'static');
    //路由
    let pathname = url.parse(req.url).pathname.replace("/","");//'/login'=>'login'
    //http://127.0.0.1:3000/news?page=2&id=1
    let extname = path.extname(pathname);


    if (!extname) {   //如果有后缀名的话让静态web服务去处理
    try {
        routes[pathname](req, res);
    } catch (error) {
        routes['error'](req, res);
    }
}


}).listen(3000);

console.log('Server running at http://localhost:3000/');
const fs = require('fs');
const path = require('path');
const url = require('url');
const ejs = require('ejs');

//私有方法
let getFileMime = function (extname) {
    var data = fs.readFileSync('./data/mime.json'); //同步方法
    let mimeObj = JSON.parse(data.toString());
    return mimeObj[extname];
}
let app={
    static :(req,res,staticPath)=>{
        //获取地址
        let pathname = url.parse(req.url).pathname;
        //pathname = pathname=="/"?"/index.html":pathname;
        let extname = path.extname(pathname);
        //读取文件
        if (pathname != '/favicon.ico'&& extname) {
            try {
                let data = fs.readFileSync('./' + staticPath + pathname);
                if (data) {
                    let mime = getFileMime(extname);
                    res.writeHead(200, { 'Content-Type': '' + mime + ';charset="utf-8"' });
                    res.end(data);
                }
            } catch (error) {
            }
        }
    },login:(req,res)=>{
        ejs.renderFile('./views/form.ejs',{},(err,data)=>{
            res.writeHead(200,{'Content-Type':'text/html;charset="utf-8"'});
            res.end(data);
        })
},news:(req,res)=>{
        //news
        res.end('news')
    },doLogin:(req,res)=>{
        let postData = '';
        req.on('data',(chunk)=>{
            postData+=chunk;
        })
        req.on('end',()=>{
            console.log(postData);
            res.end(postData);
        })
    },error:(req,res)=>{
     res.end('error')
    }
}
module.exports=app;




把pathname = pathname=="/"?"/index.html":pathname; 备注掉了就不会报错 但是保留就会报错,不保留就不能默认进入index.html页面

img

先console一下,看一下你的pathname取到的是什么东西,然后再想下面这个语句会不会导致下面出错