index.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. const express = require('express');
  2. const app = express();
  3. require('dotenv').config(); // add dotnv for config
  4. const server = require('http').createServer(app);
  5. const mongoose = require('mongoose');
  6. const bcrypt = require('bcrypt');
  7. const User = require('./db/models/User');
  8. const jwt = require('jsonwebtoken');
  9. const PORT = process.env.PORT || 4000;
  10. const HASH_KEY = process.env.HASH_KEY;
  11. const {Server} = require('socket.io');
  12. const cors = require('cors');
  13. app.get('/', (req, res) => {
  14. res.send('Hello from express server!')
  15. })
  16. app.use(cors());
  17. app.use(express.json());
  18. const io = new Server(server, {
  19. cors: {
  20. origin: "http://localhost:3000" //client endpoint and port
  21. }
  22. });
  23. io.on("connection", (socket) => {
  24. console.log(socket.id);
  25. });
  26. const db = async () => {
  27. try{
  28. const salt = await bcrypt.genSalt(2);
  29. const hashPassword = await bcrypt.hash('myPassword', salt);
  30. const user = new User({
  31. userName: 'Sergey',
  32. hashPassword: hashPassword
  33. })
  34. user.save();
  35. }catch(e){
  36. console.log(e)
  37. }
  38. }
  39. //db();
  40. const start = async () => {
  41. try {
  42. await mongoose.connect('mongodb://localhost:27017/chat')
  43. .then(() => console.log(`DB started`))
  44. server.listen(PORT, () => {
  45. console.log(`Server started. Port: ${PORT}`);
  46. })
  47. } catch (e) {
  48. console.log(e);
  49. }
  50. }
  51. start();