Как избавиться от проблемы с ошибкой сокета в почтальоне, используя nodejs API для входа и регистрации - PullRequest
1 голос
/ 30 мая 2020

Я новичок в Node.js и пытаюсь создать API входа и регистрации и сохранить эти данные в MongoDB, но когда я отправляю запрос на регистрацию, я получаю сообщение об ошибке Socket Hangup (не удалось получить ответ). Я много пробовал, но не смог отладить, почему у меня возникает эта проблема. Вот мое приложение. js код

'use strict'
var createError = require('http-errors');
var express = require('express');
var path = require('path');
const fs=require('fs');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const mongoose=require('mongoose');
const Dishes=require('./Model/schema');
const session=require('express-session');//used for creating the session
const FileStore=require('session-file-store')(session);//used to create the file for the storage of cookies
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var dishRouter = require('./routes/dishRouter');
//var promoRouter = require('./routes/promoRouter');
//var leaderRouter = require('./routes/leaderRouter');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://Sauravpandey:85ffxufexfEP3HXzPPq@saurav-5irg5.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true,useUnifiedTopology: true });
client.connect(err => {
  const collection = client.db("test").collection("devices");
  console.log('conected properly to drive');
  // perform actions on the collection object
  client.close();
});
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(session({
  name:'session-id',
  secret:'12345-67890-09876-54321',
  saveUninitialized:false,
  resave:false,
  store:new FileStore()
}))
app.use('/', indexRouter);
app.use('/users', usersRouter);
//app.use(cookieParser('12345-67890-09876-54321'));
///////////////////----------------authorization process-----------------------////////////////////
function auth (req, res, next) {
  console.log(req.session);
  if(!req.session.user){
      var err = new Error('You are not authenticated!');
      err.status=403;
      return next(err);
    }
  else{
    if(req.session.user==='authenticated'){
      next();
    }
    else{
      var err = new Error('You are not authenticated!');
      err.status = 403;
      return next(err);
    }
  }
}
app.use(auth);
app.use(express.static(path.join(__dirname, 'public')));
// modifications done 
app.use('/dishes',dishRouter);
// catch 404 and forward to error handler
app.all('/',(req,res,next)=>{
  res.statusCode=200;
  res.setHeader('Content-Type','text/plain');
  next();
});
app.listen(3000,()=>console.log("Server is started listening at port 3000"));

Вот пользователь. js файл-

    var router = express.Router();
    var mongoose=require('mongoose');
    var User=require('../Model/user');
    var bodyParser=require('body-parser');
    router.use(bodyParser.json());

    /* GET users listing. */
    router.get('/', function(req, res, next) {
      res.send('respond with a resource');
    });

    //------------------------------------- SignUp-----------------------///////////////////

    router.post('/signup',(req,res,next)=>{
      User.findOne({username:req.body.username})
      .then((user)=>{
        if(user!=null){
          var err=new Error('this user '+ req.body.username +' already exists');
          err.status=403;
          next(err);
        }
        else{
          return user.create({
            username:req.body.username,
            password:req.body.password
          });
        }
      })
      .then(user=>{
        res.statusCode=200;
        res.setHeader('Content-Type','application/json');
        res.json({status:'Registration sussesful',user: user});
      }), (err)=>next(err)
      .catch((err)=>next(err));
    });

    //---------------------------- Login Code-----------------------------------------------

    router.post('/login',(req,res,next)=>{
      if(!req.session.user){
        var authHeader=req.headers.authorization;
        if(!authHeader){
          var err=new Error('You are not authenticated!');
          res.setHeader('WWW-Authenticate','Basic');
          err.status=401;
          return next(err);
        }
        var auth=new Buffer.from(authHeader.split(' ')[1],'base64').toString().split(':');
        var username=auth[0];
        var password=auth[1];
        User.findOne({username:username})
        .then((user)=>{
          if(user===null){
            var err=new Error('User '+username +' does not exist');
            err.status=403;
            return next(err);
          }
          else if(user.password!=password){
            var err=new Error('Your password is incorrect');
            err.status=403;
            return next(err);
          }
          else if(user.username===username&&user.password===password){
            req.session.user='authenticated';
            res.statusCode=200;
            res.setHeader('Content-Type', 'text/plain');
            res.end('You are authenticated!')
          }
        }).catch((err)=>next(err));
      }
      else{
          res.status=200;
          res.setHeader('Content-Type','text/plain');
          res.end('You are already authenticated');
      }
    });

    //--------------------------------- Logout code-------------------------------------------

    router.get('./logout',(req,res)=>{
      if(req.session){
        req.session.destroy();
        res.clearCookies('session_id');
        res.redirect('/');
      }
      else{
        var err = new Error('You are not logged in!');
        err.status = 403;
        next(err);
      }
    });

    module.exports = router;```

I have created the schemas properly I think there is some error in app.js or users.js file.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...