首页 > 解决方案 > TypeError:无法读取未定义的属性“电子邮件”,如何解决

问题描述

我制作了一个 express 和 firebase 应用程序,在该应用程序中,我使用 firebase auth 和使用 express 路由来注册我的用户。代码是这样的

我使用 POSTMAN 进行了测试,它向我显示了这个错误 [这是构建日志][1] https://i.stack.imgur.com/tshAw.png

const app = express();

const firebase = require('firebase/app')
require('firebase/auth')

firebase.initializeApp({
    apiKey: "AIzaSyBrrAjBnmwqwDYGZ0iAmb3CwOa2jb7aqf4",
    authDomain: "shine-online.firebaseapp.com",
    databaseURL: "https://shine-online.firebaseio.com",
    projectId: "shine-online",
    storageBucket: "shine-online.appspot.com",
    messagingSenderId: "74335759103",
    appId: "1:74335759103:web:f225703b6bdae0efc0baca"
})


const PORT = process.env.PORT || 5000;

//routes
app.get('/api', (req, res) => {
    res.send('Hello World')
})

//signup route
app.post('/signup', (req, res) => {
    const newUser = {
        email: req.body.email,
        password: req.body.password,
        confirmPassword: req.body.confirmPassword,
        username: req.body.username,
    }

    
    firebase.auth().createUserWithEmailAndPassword(newUser.email,newUser.password)
        .then(data => {
            return res.status(201).json({ message: `user ${data.user.uid} signed yp suceesfully`})
         })
         .catch((err) => {
            console.error(err)
            return res.status(500).json({ error: 'something gone wrong' })
        })
        
})


app.listen(PORT, ()=> {
    console.log(`Listening on the PORT ${PORT}`)
} )```


  [1]: https://i.stack.imgur.com/tshAw.png

标签: node.jsfirebasefirebase-authentication

解决方案


我的猜测是 req.body 未定义,可能是因为正文未解析为 JSON。在路由之前将 json 解析器添加到您的项目中:

const PORT = process.env.PORT || 5000;

//  JSON parser middleware
app.use(express.json());

//routes
app.get('/api', (req, res) => {
    res.send('Hello World')
})

express.json 是一个中间件,它将您的请求正文解析为 JSON。

默认情况下,只会解析带有Content-Type: application/json头的请求。


推荐阅读