node.js - 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
解决方案
我的猜测是 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头的请求。
推荐阅读
- postman - 如何在 netsuite 中支付特定发票?使用客户付款
- html - 如何将每个孩子与第 n 个孩子同时定位在 flex/grid/whatever 中?
- javascript - 类型'{ props: ReactNode; 上不存在属性'className' }'
- android - Spannable String Builder不应用字体
- html - 文字装饰:无;当父元素显示为 flex 时不起作用
- reactjs - IONIC React 无限滚动
- flutter - 如何在运行集成测试时指定构建变体?
- javascript - 用Javascript从PHP数据库访问表
- java - 使用度量 spring_cloud_stream_binder_kafka_offset 进行 kafka 滞后
- php - 订单状态更改时的 WooCommerce 严重错误