HOW to implement backend with "EXPRESS" and frontend with "NUXT.JS" - javascript

I am new at web development and saying sorry for this question. THE thing is that i have done a serverside with Express and connected to MongoDB, have already established the connection where i can insert, select, delete information, but don't know how to make Frontend side with NUXT.JS, i want to put 4 buttons in frontend which will be select, insert, delete buttons . Here is my backend:
const express = require('express');
const bodyParser = require('body-parser');
// create express app
const app = express();
// parse requests of content-type - application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }))
// parse requests of content-type - application/json
app.use(bodyParser.json())
// Configuring the database
const dbConfig = require('./config/database.config.js');
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
// Connecting to the database
mongoose.connect(dbConfig.url, {
useNewUrlParser: true
}).then(() => {
console.log("Successfully connected to the database");
}).catch(err => {
console.log('Could not connect to the database. Exiting now...', err);
process.exit();
});
// define a simple route
app.get('/', (req, res) => {
res.json({"message": "Welcome to EasyNotes application. Take notes quickly. Organize and keep track of all your notes."});
});
// Require Notes routes
require('./app/routes/note.routes.js')(app);
// listen for requests
app.listen(3000, () => {
console.log("Server is listening on port 3000");
});

Related

How to work on a hosted Website and make changes?

So I have a full stack website and the frond end is hosted on netlify via github and the backend is hosted on heroku. When I make changes on front end I have to push each change to github in order to see the result. I am a newbie and I do not know how should I work on a project locally when all my routes are netlify and heroku routes.
This is the code
const express = require("express");
const path = require("path");
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const cookieParser = require("cookie-parser");
const cors = require("cors");
const User = require("./models/userModel");
dotenv.config();
// set up server
const app = express();
app.listen(process.env.PORT || 5000, () =>
console.log(`Server started on port: ${process.env.PORT || 5000 }`)
);
app.get("/test", (req, res) => {
res.send("It works");
});
app.use(express.json());
app.use(cookieParser());
app.use(
cors({
origin: "https://awesome-murdock-.netlify.app/",
credentials: true,
})
);
// connect to mongoDB
mongoose.connect(
process.env.MONGODB_URI,
{
useNewUrlParser: true,
useUnifiedTopology: true,
},
(err) => {
if (err) return console.error(err);
console.log("Connected to MongoDB");
}
);
// sign
// set up routes
app.use("/auth", require("./routers/userRouter"));
app.use("/customer", require("./routers/customerRouter"));
app.get('/', (req, res) => {
res.send('Hi')
})
as you can see cors is ponting to my netlify app and it has not connection with my back end and the same is with backend

Implementing socket.io in mongoDB and Angular it is throwing errors Cannot GET /socket.io/

I am developing an angular application which I need to use notifications for example.
I have a user which can add friends and then I can sent a friend request as in facebook and then the other user will be notificate in realtime for example You have one new notification, this user wants to be friends.
If anyone has better idea than socket.io I am free to listen and to learn
The problem it is that I get everytime Cannot GET /socket.io/
Request URL: http://localhost:4200/socket.io/?EIO=3&transport=polling&t=NVvJf99
Request Method: GET
Status Code: 404 Not Found
Remote Address: 127.0.0.1:4200
I can show the list who sent me friend but I need everytime to reload page to see new requests.
I am using socket.io in both frameworks.
Angular I have installed with npm and the same in the mongoDB.
My server.js that is what I use for the requests and responses in frontend.
Server.js
const express = require('express');
const mongoose = require('mongoose');
const http = require('http');
const cors = require('cors');
const routes = require('./src/app/routes/routes');
const path = require('path');
const socketIO = require('socket.io');
const app = express();
const server = http.Server(app);
mongoose.connect('mongodb+srv://vip:admin#test-name-sn4qu.mongodb.net/test?retryWrites=true&w=majority'
, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false
});
app.use(cors());
const io = socketIO(server);
app.set(io);
app.use(express.json({limit: '50mb'}));
app.use(express.urlencoded({limit: '50mb', extended: true}));
app.use('/images', express.static(path.resolve(process.cwd(), '../images')));
app.use(routes);
mongoose.set('useNewUrlParser', true);
mongoose.set('useFindAndModify', false);
mongoose.set('useCreateIndex', true);
app.get("/", (req, res) => {
res.json({ message: "Welcome to application." });
});
const PORT = process.env.PORT || 5000;
server.listen(PORT);
And then in the friendController I use something like this.
function createNewRequest(req, res, next) {
const io = req.app.get('io');
friendService.createNewRequest(req.body)
.then(res.status(200).json({ message: 'Friend added successfully' }),
io.emit('newTaskAdded'))
.catch(err => next(err));
}
And then in the frontend I do have something like this.
And I am having an error which says
Cannot find namespace 'SocketIOClient'. private socket:SocketIOClient.Socket;
import * as io from "socket.io-client";
constructor() {
this.socket = io();
}
ngOnInit(): void {
this.LoadRequestingFriends();
this.socket.on('newTaskAdded', () => {
this.LoadRequestingFriends();
})
}

How to send ws message from route request

I've been trying to create an app that uses telegram-bot, express server and react app. Therefore, I need to create a POST request from telegram-bot to express, while express sends POST data to a websocket connection:
const express = require("express");
const app = express();
const expressWs = require("express-ws")(app);
// handles bot request
app.post("/request", (req, res) => {
playlist.push(req.body.url);
res.status(200).send({ message: "video is added to playlist" });
});
// after handling requst data must go here and send ws message to client side
app.ws("/echo", (ws, req) => {
ws.on("message", msg => {
ws.send(`msg is = ${msg}`);
});
});
Am I making it right, and if so, how to call ws.send from after handling request at app.post route?
From the understanding I have from your question, here is an updated version of your code that does exactly what you want.
I replaced the express-ws package with ws since that would be sufficient for your use case.
The express server runs on port 8080 while the websocket server runs on port 8081 since are different protocols and would not run on the same port (You can make it work but I do not recommend it See this question
const express = require("express");
const Websocket = require('ws');
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
const wss = new Websocket.Server({ port: 8081 });
wss.on('connection', (ws) => {
console.log('One client connected');
ws.on("message", msg => {
ws.send(`msg is = ${msg}`);
});
})
// handles bot request
app.post("/request", (req, res) => {
// Broadcast URL to connected ws clients
wss.clients.forEach((client) => {
// Check that connect are open and still alive to avoid socket error
if (client.readyState === Websocket.OPEN) {
client.send(url);
}
});
res.status(200).send({ message: "video is added to playlist" });
});
app.listen(8080, () => {
console.log('Express listening on 8080');
console.log('Websocket on 8081');
});
Tested via curl with curl -d 'url=https://example.com/examplesong' localhost:8080/request I had a client connected to ws://localhost:8081 and everything looks good.

Node server response is HTML after adding catch-all to allow react-router to work

I have been developing a node backend, react front end web app for a couple months. It has working just fine when I started the server via nodemon and the front end with npm start. But now that I am getting ready to host an alpha version and ran 'npm run build' I've been running into issues.
It seems to be stemming from the interaction of accessing the app from the server's port and react-router. I added a catch-all endpoint app.get('/*'...) to my server to allow the react-router to work. So now when the front requests data, the response is HTML not the array I want.
I feel like there is a simple solution to this, but I just don't see it yet. I looked into using HashRouter instead of BrowserRouter, but unfortunately I can't use that because I am using MSAL Active Directory for login.
server/index.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors')
require('dotenv').config();
const massive = require('massive');
const session = require("express-session");
const morgan = require('morgan');
const path = require('path');
const ctrl = require(`./controllers/controller.js`);
//Middleware
const app = express();
app.use(bodyParser.json());
app.use(cors());
app.use(express.static(__dirname + './../build'));
app.use(morgan('dev'));
//Connection to Azure DB
massive(process.env.CONNECTION_STRING)
.then(db => {
console.log('Connected to Azure PostgreSQL Database')
app.set('db', db)
}).catch(err=>console.log(err))
app.use(session({
secret: process.env.SESSION_SECRET,
cookie: { maxAge: 60000 },
resave: false,
saveUninitialized: true
}));
//Endpoints
app.get('/*', function(req, res) {
res.sendFile(path.join(__dirname, './../build/index.html'), function(err) {
if (err) {
res.status(500).send(err)
}
})
})
app.get('/getallemployees/', ctrl.getAllEmployees)
app.listen(8080, () => console.log(`Listening on ${8080}`));
Put that catch-all endpoint after all the others that return data.
//Endpoints
app.get('/getallemployees/', ctrl.getAllEmployees)
app.get('/*', function(req, res) {
res.sendFile(path.join(__dirname, './../build/index.html'), function(err) {
if (err) {
res.status(500).send(err)
}
})
})

Why do I get the PUT request with POSTMAN not done?

Before embarking on the routes of my application, I have created some requests with POSTMAN of which PUT is not made to me in full.
This is my configuration of my server in ExpressJS:
const express = require('express');
const morgan = require('morgan');
const helmet = require('helmet');
const mongoose = require('mongoose');
const app = express();
// Settings
app.set('port', process.env.PORT || 3000);
mongoose.connect('mongodb://localhost/mevn-curso', {
useNewUrlParser: true,
useFindAndModify: false,
useCreateIndex: true
})
.then(db => console.log('DB is connected'))
.catch(err => console.log(err));
mongoose.set('useNewUrlParser', true);
mongoose.set('useFindAndModify', false);
mongoose.set('useCreateIndex', true);
// Middlewares
app.use(morgan('dev'));
app.use(express.json());
app.use(helmet());
// Routes
app.use('/tasks/', require('./routes/tasks'));
// Static files
app.use(express.static(__dirname + '/public'))
app.listen(app.get('port'), ()=> {
console.log('Server on port', app.get('port'));
});
It works for me normally and this is the router I am using, which is inside the tasks.js file in the routes folder:
const express = require('express');
const router = express.Router();
const Task = require('../models/Task');
router.get('/', async (req,res)=> {
const tasks = await Task.find();
res.json(tasks);
})
router.post('/', async (req,res) => {
const task = new Task(req.body);
await task.save();
res.json({
status: "Task Saved"
})
})
router.put('/:id', async (req,res)=> {
console.log(req.params._id);
console.log(req.body);
await Task.findByIdAndUpdate(req.params._id, req.body)
res.json('recivied');
console.log('Listo')
})
module.exports = router;
In console does not seem to give me any error. I make the request with normal POSTMAN, and it returns the logs of the console. Even the server answers the json and everything. But the data in the database is not changed. This does not happen with GET or POST, on the contrary, everything is going well.
Here I leave you how I make the request with POSTMAN. First of all I am going to show you the data that I already have in the database, with the get request that is normally done with the browser:
ready, when I'm making the PUT request this is my configuration in POSTMAN:
It's a json type content type because that's what I'm going to process, then comes the body:
and this is the answer in the console:
What do you think it could be?
as I see the console.log of req.params._id is undefined: change the
Task.findByIdAndUpdate(req.params.id, req.body) changed _id to id
router.put('/:id', async (req,res)=> {
console.log(req.params.id);
console.log(req.body);
await Task.findByIdAndUpdate(req.params.id, req.body)
res.json('recieved');
})

Categories