how do I redirect to another page? - javascript

I want to make a redirect to another page if the data is inserted, but for some reason it does not work. please tell me how you can do this? there were different ways, but even argulatorjs didn't help.
let express = require("express");
let app = express();
let port = 3000;
let bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
let angular = require('angular');
let mongoose = require("mongoose");
mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost:27017/test");
let nameSchema = new mongoose.Schema({
name: String,
login: String,
password: String,
authorization: Boolean
});
let User = mongoose.model("User", nameSchema);
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
app.post("/addname", (req, res) => {
let myData = new User(req.body);
myData.save()
.then(item => {
res.send("Вы успешно зарегистрировались, перенаправление...");
$window.location.href = '/CA.html';
})
.catch(err => {
res.status(400).send("Что-то пошло не так");
});
});
app.listen(port, () => {
console.log("Server listening on port " + port);
});

You can use it in your end-point like this;
app.get('/stackoverflow', (req, res) => {
// Redirect goes to stackoverflow
res.redirect('https://stackoverflow.com/');
})

Related

rendering username or id in the url with express routing

I have read some documentation on express routing and I am trying to render the logged in user's username or identification in the url. I need help getting the routing hit in my server.js to render the pages even before authentication. Where am I messing up?
Routing (profile.js)
const express = require("express");
var router = express.Router();
const User = require("../models/user");
const passport = require("passport");
const multer = require("multer");
// Profile Avatar
const upload = multer({ dest: "upload" });
// ACCOUNT ROUTES
router
.route("/profile/:id")
.get(function (req, res) {
if (req.isAuthenticated()) {
let dateObj = req.user.createdAt;
let createdDate = dateObj.toString().slice(4, 16);
let navbarLoggedIn = "partials/loggedIn-navbar.ejs";
let id = req.params.username;
console.log(id + "\n");
res.render(
"profile",
{ id: req.params.id },
{
currentUser: req.user.username,
currentCompany: req.user.company,
currentLocation: req.user.location,
currentPosition: req.user.position,
memberStatus: createdDate,
navbar: navbarLoggedIn,
}
);
} else {
res.redirect("login");
}
})
.post(function (req, res) {});
module.exports = router;
server.js
require("dotenv").config();
const express = require("express");
const session = require("express-session");
const passport = require("passport");
const path = require("path");
const ejs = require("ejs");
const logger = require("morgan");
const main = require("./routes/main");
const about = require("./routes/about");
const contact = require("./routes/contact");
const profile = require("./routes/profile");
const pricing = require("./routes/pricing");
const help = require("./routes/help");
const login = require("./routes/login");
const signup = require("./routes/signup");
const forgot_password = require("./routes/forgot-password");
const User = require("./models/user");
const multer = require("multer");
// PORT
const port = 8080;
const app = express();
// COOKIES AND SESSION
app.use(
session({
secret: process.env.SECRET,
resave: false,
saveUninitialized: true,
})
);
app.use(passport.initialize());
app.use(passport.session());
// DATABASE
require("./config/database.js");
// PASSPORT AUTHENTICATION
require("./config/passport.js");
// MIDDLEWARE
app.use(logger("dev"));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use("/public", express.static(path.join(__dirname + "/public")));
app.set("view engine", "ejs");
app.set("view cache", false);
// ROUTES
app.use("/", main);
app.use("/about", about);
app.use("/contact", contact);
app.use("/pricing", pricing);
app.use("/profile/:id", profile, (req, res, next) => {
next();
});
app.use("/help", help);
app.use("/login", login);
app.use("/signup", signup);
app.use("/forgot-password", forgot_password);
// Logout
app.get("/logout", function (req, res) {
res.clearCookie("connect.sid");
res.redirect("/");
});
app.listen(port, (err, done) => {
if (!err) {
console.log({ message: "success!" });
} else {
return err;
}
});
And here is my file structure.file structure.
views strucutre
When you define the profile router in your main server file, instead of defining one specific route, define a short prefix. In your case you'll use /profile. Then in your router simply define the rest of the route (/:id).
Example:
Server:
app.use("/profile", profile, (req, res, next) => {
next();
});
Router:
router
.route("/:id")
.get(function (req, res) {
if (req.isAuthenticated()) {
let dateObj = req.user.createdAt;
let createdDate = dateObj.toString().slice(4, 16);
let navbarLoggedIn = "partials/loggedIn-navbar.ejs";
let id = req.params.username;
console.log(id + "\n");
res.render(
"profile",
{
id: req.params.id
},
{
currentUser: req.user.username,
currentCompany: req.user.company,
currentLocation: req.user.location,
currentPosition: req.user.position,
memberStatus: createdDate,
navbar: navbarLoggedIn,
}
);
} else {
res.redirect("login");
}
});

Assistance On CRUD Operations For Express App

I don't have much experience and I'm trying to create a simple note taking application where I can use CRUD. I've gotten as far as being able to create a note but I'm stuck on what to actually put for Delete/Put.
Code Below
My app.js file:
const express = require('express');
const mongoose = require('mongoose');
const methodOverride = require("method-override")
const app = express();
const Note = require('./models/note');
const notesRouter = require('./routes/notes');
require('dotenv').config();
app.set('view engine', 'ejs');
app.use(express.urlencoded({ extended: false }));
app.use(methodOverride('_method'));
app.get('/', async (req, res) => {
const notes = await Note.find().sort('-createdAt');
res.render('index', { notes: notes });
});
mongoose.connect('mongodb://localhost/notes', {
useNewUrlParser: true,
useUnifiedTopology: true,
});
app.use('/', notesRouter);
app.listen(process.env.PORT || 8080, () => {
console.log(`Server Has Started`);
});
My notes.js file:
const express = require('express');
const router = express.Router();
const Note = require('../models/note');
router.get('/new', (req, res) => {
res.render('new');
});
router.post('/', async (req, res) => {
let note = await new Note({
title: req.body.title,
description: req.body.description,
});
try {
note = await note.save();
res.redirect('/');
} catch (e) {
console.log(e);
res.render('new');
}
});
module.exports = router;
I can't seem to find the correct code to put in so that I can actually delete or update an existing note.
I would appreciate any information and assistance.
delete operation -
router.route('/delete/:id')
.delete((req, res)=>{
const {id}=req.params;
Note.findOneAndDelete({_id:id})
.then(()=>res.send('deleted!'))
.catch(err=>res.send(err))
})
Set your own route if required, from frontend send id or something else by which you can find the document in the database, and use/replace accordingly to complete the operation.
For update a note- use put
router.route('/update/:id')
.put((req, res)=>{
const {id}=req.params;
const {updateField1, updateField2, updateField3}=req.body;
Note.findOneAndUpdate({_id:id}, {$set:{updateField1, updateField2, updateField3}})
.then(()=>res.send('Note updated!'))
.catch(err=>res.send(err))
})

Unable to get .env variables to hide api key

I am having trouble using the process.env to hide an api key. The process seems pretty straight forward, so I'm not really sure what's happening. If I plug the api key into the url it works, but when I use the .env variable it doesn't work. I've tried to console.log (process.env.WEATHER_API_KEY) and it comes up undefined.
I'm using JS, express, and node.
.env file:
WEATHER_API_KEY=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
app.js file:
require('dotenv').config();
const express = require("express");
const app = express();
const PORT = process.env.PORT || 3000;
const rp = require("request-promise");
let bodyParser = require("body-parser");
app.set("view engine", "ejs");
app.use(express.static(__dirname + "/public"));
app.use(
bodyParser.urlencoded({
extended: true
})
);
app.get("/", (req, res) => {
res.render("index");
});
app.get("/results", (req, res) => {
let query = req.query.search;
let weatherApiKey = process.env.WEATHER_API_KEY;
let weatherUrl =
"https://api.openweathermap.org/data/2.5/weather?zip=" +
query +
"&appid=" +
weatherApiKey;
rp(weatherUrl)
.then((body) => {
let data = JSON.parse(body);
res.render("results", { data: data });
console.log("DOTENV", process.env.WEATHER_API_KEY);
})
.catch(err => {
console.log(err);
});
});
app.listen(PORT, () => {
console.log("Weather App is listening on PORT:", PORT);
});

Get data from mongodb according with a value in express route

I want to get data from mongodb according with one value from an input. I implemented this, but i didn't manage to pass the value from front end to the query:
Here is the code:
var express = require("express");
var app = express();
const mongoose = require("mongoose");
const ejs = require("ejs");
app.set("views engine", "ejs");
var bodyParser = require("body-parser");
let urlencodedParser = bodyParser.urlencoded({ extended: false });
app.use(bodyParser.urlencoded({ extended: false }));
mongoose.connect("mongodb://localhost:27017/Test", { useNewUrlParser: true });
const userScheme = mongoose.Schema(
{ name: String, age: Number },
{ versionKey: false }
);
const User = mongoose.model("users", userScheme);
// Get data from input and send it to mangodb
app.post("/", urlencodedParser, function(req, res) {
// res.send('welcome, ' + req.body.newName)
console.log(req.body.newName);
const myname = req.body.newName;
});
// Fetch data from mangodb
User.find({ name: myname }, function(err, result) {
mongoose.disconnect();
if (err) return console.log(err);
// Send data to ejs file
console.log(result);
const a = result;
app.use("/", function(request, response) {
response.render("index", { user: a });
});
});
// Create server
app.listen(4000, function() {
console.log("Example app listening on port 3000!");
});
Please use following code
app.post('/', urlencodedParser, function (req, res) {
const myname = req.body.newName;
// Fetch data from mangodb
User.find({name:myname},function(err, result){
if(err) return console.log(err);
const a = result;
return res.render("index", { user: a});
});
})

Sending data on server by fetch

Can someone explain to me why after sending a request, server returns POST {} {}- I mean empty objects?
I don't know where this data is. Why did it dissapear?
I have no idea how to solve it...
index.js:
window.addEventListener("DOMContentLoaded", () => {
const form = document.querySelector("form");
form.addEventListener("submit", event => {
console.log("włącza sie");
event.preventDefault();
const name = document.getElementById("name").value;
const password = document.getElementById("password").value;
fetch("http:localhost:3000/register", {
method: "POST",
body: JSON.stringify({ name, password })
})
.then(res => {
console.log(res);
})
.catch(error => console.log(error));
});
});
//server.js:
const http = require("http");
const app = require("./app");
const port = 3000;
const server = http.createServer(app);
server.listen(port, () => {
console.log("server włączony");
});
//app.js
const loginRoute = require("./api/routes/loginRoute");
const registerRoute = require("./api/routes/registerRoute");
const verify = require("./autorization/verify");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use("/", (req, res, next) => {
console.log(req.method, req.query, req.body);
next();
});
app.use("/", loginRoute);
app.use("/", registerRoute);
app.use(verify);
based from your screenshot, there's a CORS issue. You can overcome that using
https://github.com/expressjs/cors middleware
var cors = require('cors');
app.use(cors());
or enable CORS for the specific route only
app.use('/', cors(), registerRoute);
registerRoute:
const express = require('express');
const router = express.Router();
const register = require('../../mongo/register');
router.post('/register',register);
module.exports = router;
register.js:
const mongo = require('./database');
const User = require('../api/patterns/user');
const register = (req,res)=>{
const toSave = new User(req.body);
User.findOne({name: req.body.name},(err,name)=>{
if(err) throw err;
if(!name){
toSave.save( (err)=> {
if (err) throw err;
console.log('user zapisany');
});
}else{
console.log('juz taki istnieje');
}
});
};
app.js:
const loginRoute = require('./api/routes/loginRoute');
const registerRoute = require('./api/routes/registerRoute');
const verify = require('./autorization/verify');
var cors = require('cors');
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/', (req,res,next)=>{console.log(req.method, req.query, req.body);
next();});
app.use('/', loginRoute);
app.use('/', registerRoute);
app.use(verify);
module.exports = app;
It still returns empty objects :(

Categories

Resources