【问题标题】:Cannot read property 'path' of undefined (Node js)无法读取未定义的属性“路径”(节点 js)
【发布时间】:2017-11-02 03:18:30
【问题描述】:

我用 react 和 node 编写应用程序,但是我的 localhost 没有运行并且我有这个错误:

UNHANDLED REJECTION TypeError: Cannot read property 'path' of undefined

所有 npm 模块都已安装,但此错误不允许启动我的项目。这是我第一次尝试用节点编写代码,所以答案可能就在附近。 下面是我的node.js:

const _ = require("lodash")
const Promise = require("bluebird")
const path = require("path")
const select = require(`unist-util-select`)
const fs = require(`fs-extra`)

exports.createPages = ({ graphql, boundActionCreators }) => {
  const { upsertPage } = boundActionCreators

  return new Promise((resolve, reject) => {
    const pages = []
    const blogPost = path.resolve("./src/templates/blog-post.js")
    resolve(
      graphql(
        `
      {
        allMarkdownRemark(limit: 1000) {
          edges {
            node {
              fields {
                slug
              }
            }
          }
        }
      }
    `
      ).then(result => {
        if (result.errors) {
          console.log(result.errors)
          reject(result.errors)
        }

        // Create blog posts pages.
        _.each(result.data.allMarkdownRemark.edges, edge => {
          upsertPage({
            path: edge.node.fields.slug, // required
            component: blogPost,
            context: {
              slug: edge.node.fields.slug,
            },
          })
        })
      })
    )
  })
}

// Add custom slug for blog posts to both File and MarkdownRemark nodes.
exports.onNodeCreate = ({ node, boundActionCreators, getNode }) => {
  const { addFieldToNode } = boundActionCreators
  if (node.internal.type === `File`) {
    const parsedFilePath = path.parse(node.relativePath)
    const slug = `/${parsedFilePath.dir}/`
    addFieldToNode({ node, fieldName: `slug`, fieldValue: slug })
  } else if (node.internal.type === `MarkdownRemark`) {
    const fileNode = getNode(node.parent)
    addFieldToNode({
      node,
      fieldName: `slug`,
      fieldValue: fileNode.fields.slug,
    })
  }
}

【问题讨论】:

  • 你能告诉我错误发生在哪一行吗?
  • 它没有准确显示行数,但它显示了:D:\IT\Valeria\Work\Project\client-only-paths\node_modules\bluebird\js\release\async .js:61 fn = function () { throw arg; };

标签: javascript node.js reactjs path


【解决方案1】:

我认为你的问题在这里:

   ).then(result => {
    if (result.errors) {
      console.log(result.errors)
      reject(result.errors)
    }

您没有在 if 块中提前返回,因此该函数将继续并尝试在之后执行所有操作。

相反,只需在其中抛出一个 return:

return reject(result.errors) // Now will not continue

但更具体地说,您的 Promise 中没有错误处理程序,这就是您看到 UNHANDLED REJECTION 警告的原因。

【讨论】:

  • 不幸的是,它没有帮助,但我修复了它。我删除了 npm 模块,重新启动计算机并重新安装 :)
  • 对不起 :( 祝你好运
猜你喜欢
  • 2017-09-10
  • 1970-01-01
  • 1970-01-01
  • 2017-03-12
  • 2018-11-30
  • 2018-05-15
  • 2016-11-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多