首页 > node报错cannot call method ’slice‘ of undefined

node报错cannot call method ’slice‘ of undefined

我的代码如下所示:

var http = require('http');
var url = require('url');
var items = [];
var server = http.createServer(function(req,res){
    switch(req.method){
        case 'POST':
                    var item = '';
                    req.setEncoding('utf-8');
                    req.on('data',function(chunk){
                        item += chunk;
                    });
                    req.on('end',function(){
                        items.push(item);
                        res.end('OK\n');
                    });
                    break;
        case 'GET':
                    items.forEach(function(item,i){
                        res.write(i+')'+item+'\n');
                    }); 
                    res.end("OK");
                    break;      
        case 'DELETE':
                    var path = url.parse(req.url).parthname;
                    var i = parseInt(path.slice(1),10);
                    if (isNaN(i)) {
                        res.statusCode = 400;
                        res.end('invalid item in');
                    }else if (!items[i]){
                        res.statusCode = 404;
                        res.end('item not found');
                    }else{
                        items.splice(i,1);
                        res.end('OK\n');
                    }
                    break;
    }
});
server.listen(3000);

在DELETE分支中,程序报错,提示cannot call method 'slice' of undefined

slice函数应该是javascript自带的函数,node应该识别啊!


解决思路:
1. cannot call method 'slice' of undefined 已经说明了,是在一个 undefined 的值上调用 slice()。说明你的 path=undefined
2. 如果新手看不懂这个错误的意思, console.log(path), 也能解决问题。

答案:
parthname 属性名写错了 应该为 pathname

PS: 应该学会多调试和正确看懂错误提示。调试的过程中,也能提高自己对代码的理解。纸上得来终觉浅:自己一番调试解决问题了,总会收获意外的东西

【热门文章】
【热门文章】