繁体   English   中英

Node.js TypeError:无法读取未定义的属性“作者”

[英]Node.js TypeError: Cannot read property 'author' of undefined

(更新)

问题:我无法返回我所有的测试数据(如图所示)没有数据显示我期望的应该是->

{"data":[{"id": 1,"title": "title A","content": "content A","createTime": 1612708329045,"author": "Alisa"}, {"id" : 2,"title": "title B","content": "content B","createTime": 1612708333855,"author": "Alisa"}],"errno":0}


来自终端的错误消息:

PS C:\Users\jiann\Desktop\JS\Nodejs> node www.js
internal/modules/cjs/loader.js:883
  throw err;
  ^

Error: Cannot find module 'C:\Users\jiann\Desktop\JS\Nodejs\www.js'
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:880:15)
    at Function.Module._load (internal/modules/cjs/loader.js:725:27)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
    at internal/main/run_main_module.js:17:47 {
  code: 'MODULE_NOT_FOUND',
  requireStack: []
}


我不知道哪里出了问题:(。如果需要更多详细信息,请告诉我,感谢您的帮助!

我的代码如下:

代码块 1 说明:如果成功获取数据和消息,显示“errno”:0,如果没有,则显示“errno”:-1

class BaseModel {
        constructor(data, message) {
            if (typeof data === 'string') {
                this.message = data
                data = null
                message = null
            }
            if (data) {
                this.data = message
            }
            if (message) {
                this.message = message
            }
        }
    }
    class SuccessModel extends BaseModel {
        constructor(data, message) {
            super(data, message)
            this.errno = 0
        }
    }
    class ErrorModel extends BaseModel {
        constructor(data, message) {
            super(data, message)
            this.errno = -1
        }
    }
    module.exports = {
        SuccessModel,
        ErrorModel
    }

代码块 2 说明:

为我的博客和用户设置路由器。 此代码块将设置JSON中的数据格式,设置URL路径,解析查询,如果没有找到路由器则返回404。

const querystring = require('querystring')
    const handleBlogRouter = require('./blog-1/src/router/blog')
    const handleUserRouter = require('./blog-1/src/router/user')

    const serverHandle = (req, res) => {
        // set JSON
        res.setHeader('Content-type', 'application/json')

        //get path
        const url = req.url
        req.path = url.split('?')[0]

        //parse query
        req.query = querystring.parse(url.split('?')[0])

        //set blog router
        const blogData = handleBlogRouter(req, res)
        if (blogData) {
            res.end(
                JSON.stringify(blogData)
            )
            return
        }

        //set user router
        const userData = handleUserRouter(req, res)
        if (userData) {
            res.end(
                JSON.stringify(userData)
            )
            return
        }
        
        //no router
        res.writeHead(404, {"Content-type": "text/plain"})
        res.write("404 Not Found\n")
        res.end()
    }

    module.exports = serverHandle


代码块 3 说明:使用 GET 和 POST 要求来自路径的数据 -> '/api/blog/list' '/api/blog/detail' '/api/blog/new' '/api/blog/update' '/ api/博客/del'

const { getList, getDetail } = require('../controller/blog')
    const { SuccessModel, ErrorModel } = require('../model/resModel')

    const handleBlogRouter = (req, res) => {
        const method = req.method // GET POST
        

        
        if (method === 'GET' && req.path === '/api/blog/list') {
            const author = req.query.author || ''
            const keyword = req.query.keyword || ''
            const listData = getList(author, keyword)
            return new SuccessModel(listData)
        }

        
        if (method === 'GET' && req.path === '/api/blog/detail') {
            const id = req.query.id
            const data = getDetail(id)
            return new SuccessModel(data)
        }

        
        if (method === 'POST' && req.path === '/api/blog/new') {
            return {
                msg: 'dummy'
            }
        }

        
        if (method === 'POST' && req.path === '/api/blog/update') {
            return {
                msg: 'dummy'
            }
        }

        
        if (method === 'POST' && req.path === '/api/blog/del') {
            return {
                msg: 'dummy'
            }
        }
    }

    module.exports = handleBlogRouter)

代码块 4 说明:这是我的两个测试数据。

const getList = (author, keyword) => {
        //fake data
        return [
            {
                id: 1, 
                title: 'title A',
                content: 'content A',
                createTime: 1612708329045,
                author: 'Alisa'
            },
            {
                id: 2, 
                title: 'title B',
                content: 'content B',
                createTime: 1612708333855,
                author: 'Amanda'
            }
        ]
    }

    module.exports = {
        getList
    })

此错误表示您正在访问<?>.author ,但<?>undefined

例如,如果您的错误在这里:

    if (method === 'GET' && req.path === '/api/blog/list') {
        const author = req.query.author || ''
//      ^^^ TypeError: Cannot read property 'author' of undefined
        const keyword = req.query.keyword || ''

这意味着req.queryundefined 如果有可能出现某些东西,您可以使用可选链接

let foo = undefined;

foo.bar; // TypeError: Cannot read property 'bar' of undefined
foo?.bar; // => undefined
foo?.bar.baz; // TypeError: Cannot read property 'baz' of undefined
foo?.bar?.baz; // => undefined

该错误是因为您的服务器未正确启动,因此您期望的所有这些值都将不可用。 你用什么命令来启动服务器?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM