我正在尝试以下代码:
firebase
.auth()
.signInWithEmailAndPassword(this.email, this.password)
.then(function(user) {
let token = user.getIdToken(true);
if (token) {
axios.post('http://localhost:3000/verify_token', {
idtoken: token
})
但我在浏览器中收到错误:
TypeError: Converting circular structure to JSON
at JSON.stringify (<anonymous>)
at transformRequest (defaults.js?2822:51)
at transform (transformData.js?4cd5:16)
at Object.forEach (utils.js?7061:224)
at transformData (transformData.js?4cd5:15)
at dispatchRequest (dispatchRequest.js?c4bb:37)
at <anonymous>
如何将令牌发送到外部服务器?令牌的JSON属性并不清楚。他们来自&#34; a&#34;到&#34;我&#34;。
答案 0 :(得分:1)
根据getIdToken()的文档,它会返回一个包含字符串的promise,这是您正在寻找的令牌。
现在,您的代码假定直接返回字符串。相反,您必须在该承诺上调用then()来获取您的请求的实际令牌。
答案 1 :(得分:0)
user.getToken()
返回承诺不是令牌值,您需要在承诺上致电then
或使用await
使用then
let token = user.getIdToken(true).then(token =>
{
if (token) {
axios.post('http://localhost:3000/verify_token', {
idtoken: token
});
}).catch(e => {/*DO SOMETHING*/});
使用await
try{
let token = await user.getIdToken(true);
if (token) {
axios.post('http://localhost:3000/verify_token', {
idtoken: token
});
}catch(e){/*DO SOMETHING*/}
答案 2 :(得分:0)
我希望这会对其他所有人有所帮助。
在您的 auth.service.ts 文件中:
import { Injectable } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/auth';
import { HttpClient } from '@angular/common/http';
import * as firebase from 'firebase/app';
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private afAuth: AngularFireAuth, private http: HttpClient) {}
getIdToken() {
// Call getIdToken() from your login component
// And then listen to the auth status change
this.afAuth.auth.onAuthStateChanged(userAuth => {
if (userAuth) {
// When user is signed in, you can get their user id as a test
console.log('User ID: ' + userAuth.uid);
// Get Id Token of the currently signed in user
firebase.auth().currentUser.getIdToken()
.then(function(idToken) {
console.log('idToken is: ', idToken);
// Return this idToken and get it in the next promise
return idToken;
})
.then((token) => {
const idTokenJSON = {
id_token: token
};
// Always set the response type in your http request.
// Here the type is {message: string, data: {id_token: string}}
this.http.post<
{message: string, data: {id_token: string}}
>('http://server_domain.com/check_id_token', idTokenJSON)
.subscribe((response) => {
console.log('response data: ', response.data);
console.log('response message: ', response.message);
});
})
.catch(function(error) {
// Handle error
});
} else {
console.log('No user is signed in.');
}
});
}
}
获取ID令牌后,必须链接另一个将令牌发送到服务器的Promise。在这里,我正在使用Angular HttPClient。但是常规的HTTPS POST请求也应该这样做,如下所示:
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://server_domain.com/check_id_token');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
console.log('Signed in as: ' + xhr.responseText);
};
xhr.send('idtoken=' + token);
请告诉我这是否有帮助。