У меня есть проект страницы входа в систему для перенаправления администратора на панель управления. он использует expressjs на стороне сервера и angularjs как на стороне клиента.
эта страница входа на стороне клиента использует angularjs
//this is the angular controller that use for get the data from login form
(function () {
'usestrict';
"the initialize angular module"
angular.module("myAdmin",[]).controller('loginCtrl', function($scope, $http){
$scope.login = function() {
var userEmail = $scope.user.email;
var userPassword = $scope.user.password;
$http.post('/admin/',{useremail:userEmail, userpassword:userPassword});
}
})
})();
это страница входа в систему html
<!DOCTYPE html>
<html lang = "en" >
<head>
<title>Awi Admin</title>
<meta charset = "utf-8">
<meta name = "description" content = "Aplikasi AWI Realtime Lelang Menggunakan Framework ExpressJS dan Realtime Database Firebase">
<meta name = "author" content = "Muhammad Abubakar Siddiq - MAS Abbe">
<meta http-equiv = "X-UA-Compatible" content = "IE=edge">
<meta content = "width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name = "viewport">
<link rel='stylesheet' href='/stylesheets/login.css'/>
<link rel = "stylesheet" type = "text/css" href = "/stylesheets/font-awesome.min.css">>
</head>
<body ng-app = "myAdmin">
<div class = "container">
<div class = "profile">
<button class = "profile__avatar" id = "btn_avatar">
<img src = "/images/avatar.png" alt = "Avatar" />
</button>
<div class = "profile__form">
<div class = "profile__fields">
<h3 class = "text-center">Welcome Admin Lelang</h3>
<form name = "login-form" role = "form" ng-controller = "loginCtrl" novalidate>
<div class = "fields">
<input type = "text" class = "input" placeholder = "Username" ng-model = "user.email" required/>
<span style = "color:red" ng-show = "login-form.email.$dirty && login-form.user.$invalid">
<span ng-show = "login-form.email.$error.required">Username is required.</span>
</span>
</div>
<div class = "fields">
<input type = "password" class = "input" required-pattern=.*\S.* placeholder = "password" ng-model = "user.password"/>
<span style = "color:red" ng-show = "login-form.password.$dirty && login-form.user.$invalid">
<span ng-show = "login-form.password.$error.required">Password is required.</span>
</span>
</div>
<div class = "alert alert-warning" ng-show = "login-form.email.$error.email">
<em class = "fa fa-lg fa-warning"> </em>Peringatan, username atau password salah
</div>
<div class = "profile__footer">
<center>
<button class = "btn" id = "btn-submit" ng-click = "login()">LOG IN</button>
</center>
</div>
</form>
</div>
</div>
</div>
</div>
<script>
document.getElementById('btn_avatar').addEventListener('click',
function () {
[].map.call(document.querySelectorAll('.profile'),
function(el) {
el.classList.toggle('profile--open');
});
}
);
</script>
<script type = "text/javascript" src = "/javascripts/jquery-1.11.1.min.js"></script>
<script type = "text/javascript" src = "/javascripts/bootstraps/bootstrap.min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.7.2/angular.min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.7.2/angular-resource.min.js"></script>
<script type = "text/javascript" src = "/javascripts/login.js"></script>//==> this is the function for login that call the angular controller
</body>
</html>
и этот index.js как серверный expressjs
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const express = require('express');
const engines = require('consolidate');
const path = require('path');
const session = require('express-session');
const bodyParser = require('body-parser');
const app = express();
const firebaseApp = admin.initializeApp(
functions.config().admin
);
const HTTP_SERVER_ERROR = 500;
app.engine('hbs', engines.handlebars);
app.set('views', './views');
app.set('view engine', 'hbs');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing
app.get('/admin/', (req, res)=>{
res.set('Cache-Control', 'public, max-age=300, s-maxage=600');
res.render('index')
});
//this is the functions post for server side express
app.post('/admin/', (req, res)=>{
console.info('post login'+req.body.userEmail, req.body.userPassword);
admin.auth().signInWithEmailAndPassword(req.body.userEmail, req.body.userPassword)
.then(function (user) {
res.render('/admin/home');
console.info("success login admin".user.uid);
})
.catch(function(err){
res.send("fail");
console.info("Error while executing firebase.auth() ",err);
});
});
exports.app = functions.https.onRequest(app);
это мой проект в github проект
Моя проблема для этого проекта - это данные от пост-функции контроллера angular до пост-рендеринга expressjs, обнаруженного как неопознанный. может кто-нибудь просветить меня, в чем причина ?? и как это решить. эта функция не запускает функции firebase auth ()



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Попробуйте как,
$http({
method: 'POST',
url: '//admin/',
data: {useremail:userEmail, userpassword:userPassword}
}).then(function(rsp){...});
мне нужно было использовать это в экспрессе?
нет, это должно быть из angularjs
все еще есть та же проблема, неопознанная :(
о, это странно, вы можете проверить, есть ли ошибка на консоли
консоль говорит: «Возможно необработанное отклонение». но проблема в том, почему экспресс обнаруживает данные как неопознанные
когда консольный журнал на стороне клиента определенно идентифицирует данные
о, вы можете просто напечатать console.info (req)
все еще есть та же проблема. неопознанный
это угловой контроллер
(function () {
'usestrict';
"the initialize angular module"
angular.module("myAdmin",[]).controller('loginCtrl', function($scope, $http){
$scope.login = function() {
var userEmail = $scope.user.email;
var userPassword = $scope.user.password;
var myObject = {useremail:userEmail, userpassword:userPassword}
$http({
method: 'POST',
url : '/admin/',
data : JSON.stringify(myObject)
});
}
})
})();
это функции expressjs
app.post('/admin/', (req, res)=>{
console.info("####Success");
console.info('post login '+req.body.useremail, req.body.userpassword);
admin.auth().signInWithEmailAndPassword(req.body.useremail, req.body.userpassword)
.then(function (user) {
res.render('/admin/home');
console.info("success login admin".user.uid);
})
.catch(function(err){
res.send("fail");
console.info("Error while executing firebase.auth() ",err);
});
});
после консультации с удаленным рабочим столом, окончательное исправление
Похоже, вы разместили больше кода, чем было бы разумно для решения вашей проблемы. Вам нужно лучше решить эту проблему самостоятельно. Мы не отладчики. Вам нужно изолировать проблему и оттуда отладить. Прочтите Как спросить и о том, как создать минимальный воспроизводимый пример, поскольку предоставление MCVE помогает пользователям ответить на ваш вопрос, а будущие пользователи относятся к вашей проблеме.