import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
const middlewares = [thunk]
const mockStore = configureMockStore(middlewares)
const store = mockStore()
Related
i have client side and server side files in my project using react.i have created a signup page and used atlas mongo db to store data. but whwnever iam trying to load data iam getting an error.
this is the error iam getting when i click on signup
this is the view of my mongodb project
this is my server/index.js file
import express from 'express';
import mongoose from 'mongoose';
import cors from 'cors'
import dotenv from 'dotenv';
import userRoutes from './routes/users.js'
import questionRoutes from './routes/Questions.js'
import answerRoutes from './routes/Answers.js'
const app = express();
app.use(express.json({limit:'30mb',extended:true}))
app.use(express.urlencoded({limit:'30mb',extended:true}))
app.use(cors());
dotenv.config();
app.get('/',(req,res) => {
res.send("this is a stack overflow clone API")
})
app.use('/user',userRoutes)
app.use('/question',questionRoutes)
app.use('/answer',answerRoutes)
const PORT= process.env.PORT || 5000;
const CONNECTION_URL ="mongodb+srv://hamsheena:hamshi#stackoverflow.1hzai1i.mongodb.net/myFirstDatabase?retryWrites=true&w=majority"
mongoose.connect(CONNECTION_URL,{useNewUrlParser:true,useUnifiedTopology:true})
.then(() => app.listen(PORT,() => {console.log(`server running on port ${PORT}`)}))
.catch((err) => console.log(err.msg))
routes
import express from 'express'
import { login, signup } from '../controllers/auth.js'
const router = express.Router();
router.post('/signup',signup)
router.post('/login',login)
export default router
controllers for routes
import jwt from 'jsonwebtoken'
import bcrypt from 'bcryptjs'
import users from '../models/auth.js'
export const signup = async(req,res) => {
const {name,email,password} = req.body;
try{
const existinguser = await users.findOne({email});
if(!existinguser){
return res.status(400).json({message:"User already exist"})
}
const hashedPassword = await bcrypt.hash(password,12)
const newUser = await users.create({name,email,password:hashedPassword})
const token = jwt.sign({email:newUser.email,id:newUser._id},"test",{expiresIn:'1h'});
res.status(200).json({result:newUser,token})
}
catch(error){
res.status(500).json("Something went wrong..")
}
}
export const login = async(req,res) => {
const {email,password} = req.body;
try{
const existinguser = await users.findOne({email});
if(!existinguser){
return res.status(400).json({message:"User dont exist"})
}
const isPasswordCrt = await bcrypt.compare(password,existinguser.password)
if(!isPasswordCrt){
return res.status(400).json({message:"Invalid credentials"})
}
const token = jwt.sign({email:existinguser.email,id:existinguser._id},"test",{expiresIn:'1h'});
res.status(200).json({result:existinguser,token})
}
catch(error){
res.status(500).json("Something went wrong..")
}
}
models
import mongoose from 'mongoose'
const userSchema = mongoose.Schema({
name:{type:String,required:true},
email:{type:String, required:true},
password:{type:String, required:true},
about:{type:String,},
tags:{type:[String]},
joinedOn:{type:Date,default:Date.now}
})
export default mongoose.model("User", userSchema)
now in my client side i have an api/index.js
import axios from 'axios'
const API = axios.create({baseURL:'http://localhost:5000'})
export const logIn = (authData) => API.post('/user/login',authData);
export const signUp = (authData) => API.post('/user/signup',authData);
export const postQuestion = (questionData) => API.post('/questions/Ask',questionData);
export const getAllQuestions =() => API.get('/questions/get');
export const postAnswer = (id, noOfAnswers, answerBody, userAnswered, userId ) => API.patch(`/answer/post/${id}`, { noOfAnswers, answerBody, userAnswered, userId })
//export const postAnswer = (id,noOfAnswers,answerBody,userAnswered) => API.patch(`/answer/post/${id}`,{noOfAnswers,answerBody,userAnswered})
iam new to MERN.kindly help if you have any idea.
iam not getting any errors on terminal either,both on client and server side.
client and server side terminal
I have a main file called index.js. Here, I want to do some global stuff which can be used by different js file:
const algoliasearch = require('algoliasearch');
const firebase = require('firebase');
const firebaseAdmin = require('firebase-admin');
var dotenv = require('dotenv');
var app = require('express')();
const express = require('express')
const scheduler = require('node-schedule')
const dateFormat = require('dateformat');
const OneSignal = require('onesignal-node');
const client = new OneSignal.Client('XXX', 'XXX');
const path = require('path')
const PORT = process.env.PORT || 5000
// load values from the .env file in this directory into process.env
dotenv.load();
firebaseAdmin.initializeApp({
databaseURL: process.env.FIREBASE_DATABASE_URL
});
firebase.initializeApp({
apiKey: 'XXX',
projectId: 'XXX'
});
const algolia = algoliasearch(
process.env.ALGOLIA_APP_ID,
process.env.ALGOLIA_API_KEY
);
var database = firebase.firestore();
const constant = require('./Constant.js')
const tournamentDataAccessService = require('./TournamentDataAccessService.js')
const tournamentParticipationDataAccessService =
require('./TournamentParticipationDataAccessService.js')
constant = new Constants()
My problem occurs in line constant = new Constants()
Here we need to check the Constants.js
class Constants {
constructor() {
console.log(database) // database is defined in index.js file
}
}
Compiler complains about database;. To be more precise, database can't be found. How can I access the database variable in the index.js? file? I could pass the variable as a parameter to the constructor of Constants.js but is there a different solution?
I'm trying to make a comment section using socket io in my mern stack app. When I was first developing it it works just fine but after shutting VS code down for a rest I couldn't get it to connect anymore : (((
Here's my server.js
require ('dotenv').config()
const express = require('express')
const mongoose = require('mongoose')
const cors = require('cors')
const cookieParser = require('cookie-parser')
const fileUpload = require('express-fileupload')
const { file } = require('googleapis/build/src/apis/file')
const res = require('express/lib/response')
const path = require('path')
const Comments = require('./models/comment')
const app= express()
app.use(express.json())
app.use(cors())
app.use(cookieParser())
app.use(fileUpload({
useTempFiles: true
}))
const http= require('http').createServer(app)
const io= require('socket.io')(http)
//this doesn't give back anything
io.on("connect_error", (err) => {
console.log(`connect_error due to ${err.message}`);
});
// Socket io
let users = []
io.on('connect', socket => {
console.log(socket.id + ' connected.')
// code for comments
socket.on('disconnect', () => {
console.log(socket.id + ' disconnected.')
//socketCleanup();
socket.socket.reconnect();
users = users.filter(user => user.id!== socket.id)
})
})
and here's my GlobalState.js
import React, {createContext, useState, useEffect} from 'react'
import BooksAPI from './api/BooksAPI'
import GenresAPI from './api/GenresAPI'
import UserAPI from './api/UserAPI'
import axios from 'axios'
import io from 'socket.io-client'
export const GlobalState = createContext()
export const DataProvider = ({children})=>{
const[socket, setSocket] = useState(null)
useEffect(() =>{
const socket = io()
setSocket(socket)
return ()=> socket.close()
},[])
const state={
socket
}
return (
<GlobalState.Provider value={state}>
{children}
</GlobalState.Provider>
)
}
I can't find any solution on the internet that works and I don't even know why it's not connecting : ((( please help.
I have a problem with code actually server not receives JSON or receives JSON as text
.......................................................................
.......................................................................
.......................................................................
app.js:
const config = require("config");
const express = require('express')
const bodyParser = require('body-parser');
const app = express()
app.use(bodyParser.json()) //express.json was tried
app.use(bodyParser.text()) // if do not using this json null
app.use('/api/auth',require("./routes/auth.route"))
auth.route.js
const {Router} = require("express");
const config = require("config");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const {body,validationResult} = require("express-validator");
const User = require("../models/User");
const router = Router();
//api / auth/register
router.post(
'/register',
[
body("email",'Wrong Email').notEmpty().isEmail(),
// check('password','Min Char count is 6, Password incorrect').isLength({min:6})
],
async (req,res)=>{
console.log("body",req.body)
console.log("email",req.body['email'])
req.body = JSON.parse(req.body);
console.log("body",req.body)
console.log("email",req.body['email'])
const validationErrors = validationResult(req);
console.log(validationErrors.array())
if(!validationErrors.isEmpty())
return res.status(401).json({arguments: validationErrors.array(),type:"wrongInputData"});
console.log(2)
})
and client:
import {useState, useCallback} from 'react';
const urlStart = "http://localhost:5000";
export const useHttp = () =>{
const [loadings,setLoading] = useState(false);
const [setError] = useState(null);
const request =useCallback(async (url, method = 'GET',body = null) =>{
setLoading(true);
try {
if(body) {
body = JSON.stringify(body);
}
url = urlStart+url
const response = await fetch(url,{method: method, body: body,
headers: {'Content-Type': 'application/json'},
mode:'no-cors',cache: 'no-cache',});
const data = await response.json();
if(!response.ok){
throw new Error("Smth wrong : "+data?.message);
}
setLoading(false);
return data;
}catch (e) {
setLoading(false);
setError(e.message);
throw e;
}
},[]);
const clearError = () => setError(null);
return { loadings, request,clearError}
}
I have a Typescripted nodejs server and i'm trying to define diffrent swagger paths for seperated controllers, but the swagger-ui-express module seems to only show the last defined doc in the specific route.
index.ts for X group of controllers
import express from 'express';
import passport from 'passport';
const router = express.Router();
// import all bot routes
import { authRoute } from './auth';
import { botCrudRoute } from './bot-crud';
import { aiRoutes } from './ai';
import { categoryCrudRoute } from './categories-crud';
const swaggerUi = require('swagger-ui-express');
import { botSwaggerDoc } from './swagger';
const swaggerDoc = botSwaggerDoc;
const swaggerUiOpts = {
explorer: false
};
// Swagger setup
router.use('/api-docs', swaggerUi.serve);
router.get('/api-docs', swaggerUi.setup(swaggerDoc, swaggerUiOpts));
index.ts for Y group of controllers
import express from 'express';
const router = express.Router();
// import all bot routes
const swaggerUi = require('swagger-ui-express');
import { adminSwaggerDoc } from './swagger';
const swaggerDoc = adminSwaggerDoc;
const swaggerUiOpts = {
explorer: false
};
// Swagger setup
router.use('/api-docs', swaggerUi.serve);
router.get('/api-docs', swaggerUi.setup(swaggerDoc, swaggerUiOpts));
export const adminRoutes = router;
api.ts grouping all groups of controllers
'use strict';
import express from 'express';
import { Response, Request, NextFunction } from 'express';
import { adminRoutes } from './admin';
import { botRoutes } from './bot';
// import { onboardRoutes } from './onboard';
const router = express.Router();
// router.use('/onboard', onboardRoutes);
router.use('/bot', botRoutes);
router.use('/admin', adminRoutes);
export const apiRoutes = router;
server.ts
/**
* Primary app routes.
*/
app.use('/api', apiRoutes);
example of one of the swaggerDoc's
export const botSwaggerDoc = {
'swagger': '2.0',
'info': {
'version': '1.0.0',
'title': 'Cupo embed chat bot API',
'license': {
'name': 'Internal use only'
}
the swagger-ui-express module only use the last defined document as if the server keeps reference to that document...
I was able to get around this by serving up the HTML directly for each individual api. See below:
// index.ts for X group of controllers
const apiV1Html = swaggerUi.generateHTML(
v1SwaggerDocument,
);
router.use(
'/docs',
swaggerUi.serveFiles(v1SwaggerDocument),
);
router.get('/docs', (req: any, res: any) => {
res.send(apiV1Html);
});
and for the Y group of controllers:
// index.ts for y group of controllers
const apiV2Html = swaggerUi.generateHTML(
v2SwaggerDocument,
);
router.use(
'/docs',
swaggerUi.serveFiles(v2SwaggerDocument),
);
router.get('/docs', (req: any, res: any) => {
res.send(apiV2Html);
});
Sources: https://github.com/scottie1984/swagger-ui-express/issues/65