简体   繁体   English

部署到 Heroku 但在本地运行时,React 应用程序中的“.filter 不是函数”错误消息

[英]'.filter is not a function' error message in React app when deployed to Heroku but not when running locally

I thought I was at the end of the very long road to getting my first full-stack app deployed...我以为我已经走到了部署第一个全栈应用程序的漫长道路的尽头……

Everything works fine when running locally but when using a login function on the version hosted on Heroku I get an error message "Uncaught TypeError: t[0].filter is not a function".在本地运行时一切正常,但是在 Heroku 上托管的版本上使用登录 function 时,我收到一条错误消息“未捕获的 TypeError:t[0].filter 不是函数”。

I'm not sure why it should work locally but not on Heroku when in theory the code is identical.我不确定为什么它应该在本地工作,但不能在 Heroku 上工作,因为理论上代码是相同的。 This is the code for the login function which seems to be what's causing the issue.这是登录 function 的代码,这似乎是导致问题的原因。


    const usersContext = useContext(UsersContext)

    const { users, showRegisterModal, showRegisterSuccessDialog, setCurrentUser, getUsers } = usersContext

    useEffect(() => {
      getUsers()
    }, [])

    const [loginDetails, setLoginDetails] = useState({
        loginEmail: '',
        loginPassword: ''
    })

    const { loginEmail, loginPassword } = loginDetails

    const onChange = (e) => {
        setLoginDetails({ ...loginDetails, [e.target.name]: e.target.value })
    }

    const onSubmit = (e) => {
        e.preventDefault()
      
        const userToLogin = users[0].filter(user => user.email === loginEmail)
       
        if (userToLogin.length === 0) {
            alert("User not found. Please register if you don't have an account.")
        } else if (
            userToLogin[0].password !== loginPassword
        ) {
            alert("Incorrect password")
        } else {
            setCurrentUser(userToLogin)
        
        }
        
    }

    const openRegisterModal = () => {
        showRegisterModal(true)
    }

    if (showRegisterSuccessDialog === true) {
        getUsers()
    }


    return (
   
        <div style={{width: "60%", height: "300px"}} className="d-flex justify-content-center align-items-center">
            <form className="justify-content-center">
             <div className="form-group">
                <label htmlFor="loginEmail">Email:</label>
                <input type="text" name="loginEmail" id="loginEmail" className="form-control" value={loginEmail} onChange={onChange}></input>
             </div>
             <div className="form-group">
                 <label htmlFor="loginPassword">Password:</label>
                 <input type="password" name="loginPassword" id="loginPassword" className="form-control" value={loginPassword} onChange={onChange}></input>
             </div>
             <div className="form-group d-inline-flex">
             <button className="btn btn-primary form-control" onClick={onSubmit}>Log In</button> 
             <button type="button" className="btn btn-success form-control" style={{marginLeft: "10px"}} onClick={openRegisterModal}>Register</button>
            </div>
            <p style={{opacity: `${showRegisterSuccessDialog ? 1 : 0}`, transition: "opacity 400ms"}}>Registration successful! You can now log in.</p>
            </form>
            
        </div>
       
    
    )
}

Here's the app on Heroku.这是 Heroku 上的应用程序。 You can use johndoe@gmail.com and password 123456 as an example login to recreate the issue.您可以使用 johndoe@gmail.com 和密码 123456 作为示例登录来重新创建问题。

Github repo for the project.该项目的 Github 存储库。

As an aside, are there any good resources to read up on about things behaving differently in apps run locally and deployed?顺便说一句,是否有任何好的资源可以阅读有关在本地运行和部署的应用程序中表现不同的事情?

users from the context is an [ { }, { } ].上下文中的users是 [ { }, { } ]。 so when you do users[0] it gives you an object.所以当你做用户[0]时,它会给你一个 object。 As the error states you can't apply filter on an object.由于错误状态,您不能在 object 上应用filter So change your code as因此,将您的代码更改为

const userToLogin = users.filter(user => user.email === loginEmail)

remove the [0] after users.删除用户后的 [0]。

When you try to get the users[0] your user array returns undefined and because undefined value does not has a method called .filter you get that nasty error.当您尝试获取users[0]时,您的用户数组返回undefined并且因为undefined值没有名为.filter的方法,您会得到那个讨厌的错误。

So you can so something like below to prevent that kind of behavior:所以你可以像下面这样来防止这种行为:

const userToLogin = users.length > 0 && users[0] !== 'undefined' && users[0].filter(user => user.email === loginEmail)

you are iterating over non-array block thats why it is giving you error of filter is not a function.您正在迭代非数组块,这就是为什么它给您错误的过滤器不是 function。

const userToLogin = users[0].filter(user => user.email === loginEmail)

remove user[0].filter instead use user.map((ele,index) => { if (ele.length > 0) { return ele[index].filter((elem) => elem.email === loginEmail)} })删除user[0].filter改为使用user.map((ele,index) => { if (ele.length > 0) { return ele[index].filter((elem) => elem.email === loginEmail)} })

if your array doesn't contain any thing it will simply return without any error.如果您的数组不包含任何内容,它将简单地返回而不会出现任何错误。

I've managed to solve the issue.我已经设法解决了这个问题。 It was actually nothing to do with the code in the Login.js file and everything to do with this block of code in server:js:它实际上与 Login.js 文件中的代码无关,而与 server:js 中的这段代码有关:

if (process.env.NODE_ENV === 'production') {
  app.use(express.static('client/build'))

  app.get('*', (req, res) => {
    res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'))
  })
}

It was before all my other routes when it needed to be after them.当它需要在它们之后时,它是在我所有其他路线之前。 I used a good old-fashioned console.log to look at what the getUsers() function was returning and obviously in this case it was the raw code for index.html, as it would have been for any other API request I'd tried to make.我使用了一个很好的老式 console.log 来查看 getUsers() function 返回的内容,显然在这种情况下,它是 index.html 的原始代码,因为它本来适用于任何其他 ZDB9744 请求 I7'1083ACEdDE463制作。 Hence all the weird letters appearing out of nowhere.因此,所有奇怪的字母都不知从何而来。

Every day's a school day, as they say.正如他们所说,每天都是上学日。 Thanks for everyone's answers anyway.无论如何感谢大家的回答。

I also had that problem.我也有这个问题。 Unfortunately, I put the Heroku route before the all other routes.不幸的是,我把 Heroku 路线放在所有其他路线之前。 That is the problem which I faced.这就是我面临的问题。

 app.use("/api/auth", require("./BACKEND/routes/auth")); app.use("/novel-book", require("./BACKEND/routes/novels")); app.use("/adventure-book", require("./BACKEND/routes/adventures")); app.use("/programming-book", require("./BACKEND/routes/programming")); app.use("/ol-book", require("./BACKEND/routes/ol")); app.use("/al-book", require("./BACKEND/routes/al")); app.use("/comment", require("./BACKEND/routes/comments")); //Error Handler (Should be the last piece of middleware) app.use(errorHandler); if(process.env.NODE_ENV === "production"){ app.use(express.static(path.join(__dirname, "/frontend/build"))); app.get("*", (req, res)=>{ res.sendFile(path.join(__dirname, "frontend", "build", "index.html")); }) }else{ app.get("/", (req,res)=>{ res.send("Api Running"); }) }

暂无
暂无

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

相关问题 React 应用程序在本地工作,但部署到 heroku 时出现应用程序错误 - React app working locally but application error when deployed to heroku 在 heroku 上部署时,rails-react 应用程序上的身份验证方法遇到内部服务器错误 (500) 和类型错误 - Running into Internal Server Error (500) and typeerror for authentication method on rails-react app when deployed on heroku 带有Express后端的Create-react-app在本地工作,但是在部署到heroku时路由不正确 - Create-react-app with express backend works locally but routing incorrect when deployed to heroku 部署在 Heroku 上时,图像未加载到 React 应用程序中 - Images not loading in React app when deployed on Heroku 部署到Heroku时React应用程序崩溃 - React App Crashes When Deployed to Heroku Flask + React 应用程序在部署到 Heroku 时失败 - Flask + React App Fails When Deployed to Heroku React 应用程序在 Heroku 上顺利部署,但应用程序未运行 - React app deployed smoothly on Heroku but the app is not running React 应用程序在 localhost 上运行,但在 github 或 heroku 上部署时出错。 部署时没有错误 - React app working on localhost but giving error when deployed either on github or on heroku. No error while deploying 在 Heroku 中部署时,Craco 无法构建 React 应用程序 - Craco unable to build react app when Deployed in Heroku Heroku-Express和React应用程序在部署时显示空白屏幕 - Heroku - Express and React app showing blank screen when deployed
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM