gpt4 book ai didi

javascript - 如何从客户端发送 Firebase token 并在 server.js 中接收它

转载 作者:搜寻专家 更新时间:2023-10-31 23:49:57 25 4
gpt4 key购买 nike

我想将 firebase 在客户端生成的用户 token 发送到服务器。我该怎么做?

我已经能够在客户端生成 token 并尝试将其发布到服务器,但我不断收到内部服务器错误。

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

客户端代码

        firebase.auth().currentUser
.getIdToken()
.then(function (token) {
console.log(token)
accessToken = token;


});

var mydata = {
customToken: accessToken
}

$.post('/auth',mydata, function(data, status){

console.log(data+" and status is "+ status)

})

server.js代码

app.post('/auth', function(req, res){

var token = req.body

res.render(token)



})

我希望能够读取/auth 中的 token 。我做错了什么?

最佳答案

您应该将请求放入then 函数:

firebase.auth().currentUser.getIdToken().then(function (token) {
console.log(token)
var mydata = {
customToken: accessToken
}

/* $.post('/auth',mydata, function(data, status){
console.log(data.token + " and status is " + status)
}) */
// https://stackoverflow.com/questions/16498256/posting-json-to-express-using-jquery
// https://stackoverflow.com/questions/6323338/jquery-ajax-posting-json-to-webservice
$.ajax({
url: '/auth',
type: 'POST',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(mydata),
success: function (data) {
console.log(data.token)
},
error: function(jqXHR, textStatus, errorThrown) { console.error(errorThrown) }
})
})

Firebase getIdToken 返回一个 Promise,因此代码是异步的。在这里阅读更多相关信息:https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Promise

服务器应该使用firebase-admin 包来验证 token 。示例设置:

const admin = require('firebase-admin')
let serviceAccount = null

try {
// download serviceAccount.json from Firebase
serviceAccount = require('./serviceAccount.json')
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: FIREBASE_DB_PATH
})
} catch (err) {
console.error('An error has occurred configuring Firebase')
}

并记住在 express 中解析 JSON 正文请求:

const bodyParser = require('body-parser')

...express config...

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))

然后您可以访问 token :

app.post('/auth', async (req, res) => {
/* if you are using node >= 10 use the line below,
but use this: const token = req.body.customToken */
const { customToken: token } = req.body
let decodedToken = null
// For example check token
try {
decodedToken = await admin.auth().verifyIdToken(token)
} catch (err) {
console.error('Error trying to verify the token: ' + err)
return res.status(403).json({ message: err.message })
}

return res.status(200).json({ token: decodedToken })
})

您应该查看此链接 https://medium.com/@yaniv_g/dont-use-bodyparser-json-with-jquery-post-d034c44ac7ad

关于javascript - 如何从客户端发送 Firebase token 并在 server.js 中接收它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57138098/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com