【发布时间】:2021-08-13 08:33:22
【问题描述】:
我是 Heroku、NodeJS 和 MongoDB 的新手。我在 Flutter 中创建了一个登录表单,它的后端在 NodeJS 和 MongoDB 中。我使用 Heroku 将后端连接到颤振,但是当我在邮递员上运行 URL(由 Heroku 在构建项目时给出)时,它给了我“未指定的名称”
这是我的 app.js 的代码
var body = require('body-parser');
const mongoose = require('mongoose');
var mongodb = require('mongodb')
var url = 'mongodb://localhost:27017/Mongodb'
var express = require('express');
var app = express();
app.use(body.json());
var bcrypt = require('bcrypt');
var CryptoJS = require("crypto-js")
var jwt = require('jsonwebtoken');
const router= express.Router()
const User = require('./connection');
mongoose.connect('mongodb://localhost:27017/Mongodb', { useUnifiedTopology: true, useNewUrlParser: true },function(err){
if(err){
console.log(err)
}else{
console.log("connection Successful")
}
})
// router.get('/Dashboard', (req, res) => {
// res.send('Hello World')
// })
function checkToken(req,res,result){
const header= req.headers.token;
if(typeof header !== 'undefined'){
const bearer =header.split('.');
const token = bearer[1]
//console.log(token)
req.token = token
//next();
result();
}else
res.json("Error")
}
const login = require('./routes/login')
app.post("/login", async (req, res, next) => {
console.log("login api hit")
login(req,res,next)
} )
const userDashboard = require('./routes/userdashboard')
app.post("/Dashboard",checkToken,(req,res)=> {
userDashboard(req,res);
})
const PORT = process.env.PORT || 5000
app.listen(PORT, function(){
console.log("Server is running")
})
这里是 ./routes/login
的代码var body = require('body-parser');
const mongoose = require('mongoose');
var mongodb = require('mongodb')
var url = 'mongodb://localhost:27017/Mongodb'
var express = require('express');
var app = express();
app.use(body.json());
const User = require('../connection');
var bcrypt = require('bcrypt');
var CryptoJS = require("crypto-js")
var jwt = require('jsonwebtoken');
login=(req,res,next)=>{
console.log(req.data)
User.find({"username":req.body.username},function(err,data){
if(err){
console.log("unspecified name")
res.status(400).json("unspecified name")
return;
}
else{
console.log(data.length)
if(data.length<=0)
{
res.status(300).json({
"message":"Invalid Input!"
})
}
else {
//bcrypt.compare(req.body.password,data[0].password).then(function(result) {
var bytes = CryptoJS.AES.decrypt(data[0].password, 'my-secret-key@123');
var decryptedData = JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
console.log(decryptedData)
if (req.body.password==decryptedData)
{
login = "Succesful";
var token = jwt.sign({
data: 'foobar'
}, 'secret', { expiresIn: "2 minute"})
res.status(200).json({auth: true, AccessToken:token, User:data[0]})
}
else
{res.status(300).json({
"message":"Input!"
})}
// });
}}
})
}
module.exports = login;
这是显示“login api hit”
的快照这是显示“服务器正在运行”的快照
这里是404错误和400错误
这是邮递员快照
现在请告诉我我的服务器是否正常运行?看来是!但是为什么它在邮递员上显示 "unspecified name" ? 请帮助我是这方面的新手,任何帮助将不胜感激!
谢谢!
---------------已编辑帖子--------------- ------------------------
我的数据库数据是这样的
谁能告诉我这背后的逻辑是什么?这些是从哪里来的?
----------已编辑帖子------ ---------------------------------------
这是我输入凭据时的输出!
这里是 cmd 的输出
2021-05-25T11:04:30.507933+00:00 app[web.1]: Server is running
2021-05-25T11:04:30.682233+00:00 heroku[web.1]: State changed from starting to up
2021-05-25T11:05:00.561298+00:00 app[web.1]: MongooseServerSelectionError: Could not connect to any servers in your MongoDB Atlas cluster. One common reason is that you're trying to access the database from an IP that isn't whitelisted. Make sure your current IP address is on your Atlas cluster's IP whitelist: https://docs.atlas.mongodb.com/security-whitelist/
2021-05-25T11:05:00.561320+00:00 app[web.1]: at NativeConnection.Connection.openUri (/app/node_modules/mongoose/lib/connection.js:832:32)
2021-05-25T11:05:00.561321+00:00 app[web.1]: at /app/node_modules/mongoose/lib/index.js:345:10
2021-05-25T11:05:00.561335+00:00 app[web.1]: at promiseOrCallback (/app/node_modules/mongoose/lib/helpers/promiseOrCallback.js:9:12)
2021-05-25T11:05:00.561341+00:00 app[web.1]: at Mongoose._promiseOrCallback (/app/node_modules/mongoose/lib/index.js:1135:10)
2021-05-25T11:05:00.561342+00:00 app[web.1]: at Mongoose.connect (/app/node_modules/mongoose/lib/index.js:344:20)
2021-05-25T11:05:00.561343+00:00 app[web.1]: at Object.<anonymous> (/app/app.js:13:10)
2021-05-25T11:05:00.561343+00:00 app[web.1]: at Module._compile (internal/modules/cjs/loader.js:1068:30)
2021-05-25T11:05:00.561344+00:00 app[web.1]: at Object.Module._extensions..js (internal/modules/cjs/loader.js:1097:10)
2021-05-25T11:05:00.561344+00:00 app[web.1]: at Module.load (internal/modules/cjs/loader.js:933:32)
2021-05-25T11:05:00.561344+00:00 app[web.1]: at Function.Module._load (internal/modules/cjs/loader.js:774:14)
2021-05-25T11:05:00.561345+00:00 app[web.1]: at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
2021-05-25T11:05:00.561345+00:00 app[web.1]: at internal/main/run_main_module.js:17:47 {
2021-05-25T11:05:00.561346+00:00 app[web.1]: reason: TopologyDescription {
2021-05-25T11:05:00.561346+00:00 app[web.1]: type: 'ReplicaSetNoPrimary',
2021-05-25T11:05:00.561346+00:00 app[web.1]: setName: null,
2021-05-25T11:05:00.561347+00:00 app[web.1]: maxSetVersion: null,
2021-05-25T11:05:00.561347+00:00 app[web.1]: maxElectionId: null,
2021-05-25T11:05:00.561348+00:00 app[web.1]: servers: Map(3) {
2021-05-25T11:05:00.561348+00:00 app[web.1]: 'cluster0-shard-00-02.ocarv.mongodb.net:27017' => [ServerDescription],
2021-05-25T11:05:00.561348+00:00 app[web.1]: 'cluster0-shard-00-00.ocarv.mongodb.net:27017' => [ServerDescription],
2021-05-25T11:05:00.561349+00:00 app[web.1]: 'cluster0-shard-00-01.ocarv.mongodb.net:27017' => [ServerDescription]
2021-05-25T11:05:00.561350+00:00 app[web.1]: },
2021-05-25T11:05:00.561350+00:00 app[web.1]: stale: false,
2021-05-25T11:05:00.561350+00:00 app[web.1]: compatible: true,
2021-05-25T11:05:00.561350+00:00 app[web.1]: compatibilityError: null,
2021-05-25T11:05:00.561351+00:00 app[web.1]: logicalSessionTimeoutMinutes: null,
2021-05-25T11:05:00.561351+00:00 app[web.1]: heartbeatFrequencyMS: 10000,
2021-05-25T11:05:00.561351+00:00 app[web.1]: localThresholdMS: 15,
2021-05-25T11:05:00.561352+00:00 app[web.1]: commonWireVersion: null
2021-05-25T11:05:00.561352+00:00 app[web.1]: }
2021-05-25T11:05:00.561352+00:00 app[web.1]: }
2021-05-25T11:15:57.214740+00:00 app[web.1]: login api hit
2021-05-25T11:15:57.215001+00:00 app[web.1]: {}
2021-05-25T11:16:07.230564+00:00 app[web.1]: unspecified name
2021-05-25T11:16:07.247306+00:00 app[web.1]: /app/node_modules/mongoose/lib/helpers/promiseOrCallback.js:19
2021-05-25T11:16:07.247307+00:00 app[web.1]: throw error;
2021-05-25T11:16:07.247308+00:00 app[web.1]: ^
2021-05-25T11:16:07.247308+00:00 app[web.1]:
2021-05-25T11:16:07.247309+00:00 app[web.1]: ReferenceError: print is not defined
2021-05-25T11:16:07.247310+00:00 app[web.1]: at /app/routes/login.js:19:7
2021-05-25T11:16:07.247310+00:00 app[web.1]: at /app/node_modules/mongoose/lib/model.js:4863:16
2021-05-25T11:16:07.247310+00:00 app[web.1]: at /app/node_modules/mongoose/lib/model.js:4863:16
2021-05-25T11:16:07.247311+00:00 app[web.1]: at /app/node_modules/mongoose/lib/helpers/promiseOrCallback.js:16:11
2021-05-25T11:16:07.247311+00:00 app[web.1]: at /app/node_modules/mongoose/lib/model.js:4886:21
2021-05-25T11:16:07.247312+00:00 app[web.1]: at /app/node_modules/mongoose/lib/query.js:4389:18
2021-05-25T11:16:07.247312+00:00 app[web.1]: at /app/node_modules/mongoose/lib/query.js:4424:14
2021-05-25T11:16:07.247313+00:00 app[web.1]: at cb (/app/node_modules/mongoose/lib/query.js:1895:14)
2021-05-25T11:16:07.247313+00:00 app[web.1]: at /app/node_modules/mquery/lib/collection/node.js:27:21
2021-05-25T11:16:07.247314+00:00 app[web.1]: at collectionOperationCallback (/app/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js:160:26)
2021-05-25T11:16:07.247323+00:00 app[web.1]: at Timeout.<anonymous> (/app/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js:185:11)
2021-05-25T11:16:07.247323+00:00 app[web.1]: at listOnTimeout (internal/timers.js:555:17)
2021-05-25T11:16:07.247324+00:00 app[web.1]: at processTimers (internal/timers.js:498:7)
2021-05-25T11:16:07.247324+00:00 app[web.1]: Emitted 'error' event on Function instance at:
2021-05-25T11:16:07.247324+00:00 app[web.1]: at /app/node_modules/mongoose/lib/model.js:4865:13
2021-05-25T11:16:07.247325+00:00 app[web.1]: at /app/node_modules/mongoose/lib/helpers/promiseOrCallback.js:16:11
2021-05-25T11:16:07.247325+00:00 app[web.1]: [... lines matching original stack trace ...]
2021-05-25T11:16:07.247326+00:00 app[web.1]: at processTimers (internal/timers.js:498:7)
2021-05-25T11:16:07.314225+00:00 heroku[web.1]: Process exited with status 1
2021-05-25T11:16:07.401592+00:00 heroku[web.1]: State changed from up to crashed
2021-05-25T11:16:07.409072+00:00 heroku[web.1]: State changed from crashed to starting
2021-05-25T11:16:07.240945+00:00 heroku[router]: at=info method=POST path="/login" host=attendance-demo.herokuapp.com request_id=ac9410a0-ac64-420b-b4d5-803aaa1a3fb2 fwd="111.88.134.32" dyno=web.1 connect=1ms service=10035ms status=400 bytes=234 protocol=https
2021-05-25T11:16:18.897092+00:00 heroku[web.1]: Starting process with command `node app`
2021-05-25T11:16:30.471917+00:00 heroku[web.1]: State changed from starting to up
2021-05-25T11:16:30.423428+00:00 app[web.1]: Server is running
这是我在按钮单击时调用的 authenticate.dart 文件
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
class AuthService{
Dio dio=new Dio();
login(name,password)async{
try{
return await dio.post('https://attendance-demo.herokuapp.com/login',data: {
"username":name,
"password":password
},options: Options(contentType:Headers.formUrlEncodedContentType)
);
}
on DioError catch(e){
Fluttertoast.showToast(msg: e.response.data['msg'],
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
backgroundColor: Colors.red,
textColor: Colors.white,
fontSize: 16.0
);
}
}
}
这是我创建的登录按钮代码并从身份验证类调用登录方法
RoundedButton(text:"Login", press: () {
AuthService().login(name,password).then((value){
if(value.data['success']){
token=value.data['token'];
Fluttertoast.showToast(msg: 'Authenticated',
toastLength: Toast.LENGTH_SHORT,
gravity: ToastGravity.BOTTOM,
backgroundColor: Colors.red,
textColor: Colors.white,
fontSize: 16.0);
}
【问题讨论】:
-
login函数定义在哪里? -
在 app.js 文件中,"app.post("/login", async (req, res, next) => { " 检查这一行
-
这个代码
require('./routes/login')在哪里?错误可能在那里。您正在调用login()函数,但尚未在此处发布代码。 -
@RaulSauco 我编辑了我的帖子,发布了 login() 代码,请立即查看。
-
在登录功能中,尝试控制台 req.body 而不是 req.data。连接 fn 看起来很可疑,请分享代码。
标签: node.js mongodb flutter heroku postman