I'm trying to access the body of the request in a middleware in order to perform it only if a specific field has changed (ereasing pictures only if new pictures got uploaded), but I'm not able to access the body.
I've tried to install and configure cors as well as reconfiguring body-parser in the route-specific file, as well as shuffling around the code, but nothing has helped (this is what was suggested in other questions).
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
const multer = require('multer');
const glob = require('glob');
const fs = require('fs');
const _ = require('lodash');
const urlencodedParser = bodyParser.urlencoded({ extended: false });
//MIDDLEWARE
router.use("/immobili/:_id/edit", urlencodedParser, function (req, res, next) {
console.log(req.body);
const requestedId = req.params._id;
Immobile.findOne({ _id: requestedId }, (err, immobile) => {
if (err) return console.error(err);
immobile.immagini = [];
cancellaFoto(immobile);
if (this.cancellato) {
return setTimeout(next, 1000);
} else {
return console.log("Aborted");
}
});
});
//EDIT PUT ROUTE
router.put("/immobili/:_id/edit", upload.array('immaginePrincipale', 30), function (req, res) {
const requestedId = req.params._id;
const dati = req.body;
const proprietaImmagini = req.files;
const immagini = proprietaImmagini.map(function (immagine) {
//console.log(immagine.path);
return immagine.path;
});
let vetrina;
req.body.vetrina === 'on' ? vetrina = true : vetrina = false;
Immobile.findOneAndUpdate({ _id: requestedId }, {
numeroScheda: dati.numeroScheda,
//[... ALL DATA ... ]
immagini: immagini,
}, function (err, updatedImmobile) {
if (err) return console.error(err);
res.redirect("/immobili/" + req.body.categoria + "/" + _.toLower(req.body.localita) + "/" + requestedId);
});
});
This is the form I'm using to send the data:
<form action="/immobili/<%= immobile._id %>/edit?_method=PUT" method="POST"
enctype="multipart/form-data">
//[ ... FORM INPUTS ... ]
<input type="file" name="immaginePrincipale" multiple="multiple" id="immaginePrincipale"></input>
<input type="submit" value="Pubblica">
</form>
I would expect to access the body of the request in the middleware but I get only an empty object in return.
Related
I'm new at backend programming and having diffuculty with using EJS and routes. I'm using a database as well. The problem is , a dynamic js variable cannot displaying in ejs view file. I mean "message" like "the password does not match <%= message %> Can you help me ? These are my codes. I've shortened them as much as i can do. I don't think database files are important for the solution so did not include them. Thanks !
This is my main index.js file :
const express = require("express");
const app = express();
const path = require('path');
const dotenv = require('dotenv') ;
dotenv.config({path:'./.env'})
app.set("view engine", "ejs");
app.use(express.static('public'));
app.use(express.static('node_modules'));
app.use(express.urlencoded({ extended: false })); //false yerine true da koyulabilir.
app.use(express.json());
//Define routes
app.use('/',require('./routes/pages'));
app.use('/auth',require('./routes/auth'));
app.listen(3000, () => {
console.log("Listening on port 3000");
});
This is my auth.js(controllers) file :
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const db_kullanici_auth = require("../data/kullanici_auth_db"); //it's a database importing
exports.register = async (req, res) => {
try {
// console.log(req.body) ;
// res.send("Form submitted") ;
// let query = "SELECT email FROM register;"
// const allDB = await (db_kullanici_auth.execute(query));
// const projeler_db = allDB[0];
// console.log(projeler_db);
const { company_name_reg, name_reg, surname_reg, department_name_reg, position_name_reg, password_reg, password_confirm_reg, adres_reg, adres2_reg, zip_reg, sehir_reg, ulke_reg, telefon_kodu_reg, telefon_numarasi_reg, email_reg } = req.body;
await (db_kullanici_auth.execute('SELECT email FROM register WHERE email = ? ', [email_reg], (error, results) => {
if (error) {
console.log(error);
}
if (results.length > 0) {
console.log(results);
return res.render('kayit_ol', {
message: 'Email is already in use'
});
}
else if (password_reg !== password_confirm_reg) {
console.log(results);
return res.render('kayit_ol', {
message: 'Passwords does not match'
});
}
// let hashedPassword = await bcrypt.hash(password_reg,8) ;
// console.log(hashedPassword) ;
}));
} catch (error) {
console.log(error);
}
}
This is my auth.js(routes) file :
const express = require('express') ;
const router = express.Router() ;
const authController = require('../controllers/auth');
router.post("/kayit_ol",authController.register);
module.exports = router ;
I'm trying to perform a simple .find() query on my mongodbAtlas, but the result of this query is an empty object.
this is my server file:
require("dotenv").config({ path: "./config.env" });
const { MongoClient, ServerApiVersion } = require("mongodb");
const express = require("express");
const { ServiceBroker } = require("moleculer");
const AUTH_SERVICE = require("./controller/services/auth/auth.service");
global.broker = new ServiceBroker({
nodeID: "auth",
});
const app = express();
app.use(express.json());
app.use("/auth", require("./routes/auth"));
const { PORT, URI } = process.env || 5000;
global.broker.createService(AUTH_SERVICE);
const start = async () => {
const dba = await MongoClient.connect(URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
global.db = dba.db("Auth");
try {
await dba.connect();
console.log("DATABASE CONNESSO CON SUCCESSO📡");
} catch (e) {
console.error(e);
}
await global.broker.start();
app.listen(PORT, () => console.log(`PORT IT'S UP AND RUNNING 🚀 ON ${PORT}`));
};
start();
this is my routes file:
const express = require("express");
const router = express.Router();
router.get("/register", async (req, res) => {
const data = global.db.collection("Users").find({}).toArray();
res.send(data);
});
module.exports = router;
this is how my document is populated:
{"_id":{"$oid":"6297bbc83a95b81d74882f65"},"username":"Test","email":"test#gmail.com","password":"1234"}
I think you are missing the "await" keyword after const data..... as API data fetching calls are asynchronous and required promise/ async-await to handle. Being async in nature, it moves forward to the next instruction and returns an empty array.
const express = require("express");
const router = express.Router();
router.get("/register", async (req, res) => {
const data = await global.db.collection("Users").find({}).toArray();
res.send(data);
});
module.exports = router;
While saving data to MongoDB, the characters that generated from a text area isn't generates correctly within the database, the output is just none (''), I've tried to change the input's unicode but nothing appeared to work. I will appreciate your help to let me know what I did wrong - and of course I will learn from it ;)
My whole JS' code
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
var http = require('http').Server(app)
var io = require('socket.io')(http)
var mongoose = require('mongoose')
app.use(express.static(__dirname))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
mongoose.Promise = Promise
var dbUrl = 'mongodb+srv://username:1234#cluster0.iwdr9.mongodb.net/database'
var Message = mongoose.model('Message', {
name: String,
message: String
})
app.get('/messages', (req, res) => {
Message.find({}, (err, messages) => {
res.send(messages)
})
})
app.get('/messages/:user', (req, res) => {
var user = req.params.user
Message.find({name: user}, (err, messages) => {
res.send(messages)
})
})
app.post('/messages', async (req, res) => {
try {
var message = new Message(req.body)
var savedMessage = await message.save()
console.log('saved')
var censored = await Message.findOne({ message: 'badword' })
if (censored)
await Message.remove({ _id: censored.id })
else
io.emit('message', req.body)
res.sendStatus(200)
} catch (error) {
res.sendStatus(500)
return console.error(error)
} finally {
console.log('message post called')
}
})
mongoose.connect(dbUrl, { useMongoClient: true }, (err) => {
console.log('MongoDB status is', err)
})
I want to create html content that looks something like this using node.js.
<div class="outputs">
...
</div>
I have the following code:
var mongoose = require("mongoose");
var express = require("express");
var bodyParser = require("body-parser");
var Url = require("./models/Url");
var shortId = require("shortid");
var http = require("http");
var app = express();
var { JSDOM } = jsdom;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
mongoose.connect(process.env.MLAB_URI);
app.get("/urls", (req, res, next) => {
Url.find({}, function(err, data) {
res.json(data);
console.log(data.length);
});
});
app.get("/deletebase", (req, res, next) => {
Url.deleteMany({}, function(err, data) {
res.json(data);
});
});
app.use(express.static(__dirname + "/"));
app.get("/:shortUrl", function(req, res, next) {
Url.findOne({ shortUrl: req.params.shortUrl }, function(err, findUrl) {
if (err) console.log(err);
if (!findUrl) {
return next({ status: 400, message: "unknown shorturl" });
}
res.redirect(findUrl.longUrl);
});
});
app.post("/", function(req, res) {
var url = new Url(req.body);
var hostname = req.headers.host;
var expression = /[-a-zA-Z0-9#:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()#:%_\+.~#?&//=]*)?/gi;
var regex = expression;
if (regex.test(url) === true) {
url.shortUrl = shortId.generate();
url.fullUrl = "https://" + hostname + "/" + url.shortUrl;
url.save(function(err, savedUrl) {
if (err) console.log(err);
res.redirect("https://" + hostname);
});
} else {
res.redirect("https://" + hostname);
}
});
var options = {
runScripts: "dangerously",
resources: "usable"
};
app.listen(3000, function() {
console.log("RUNNING");
});
I want to get length of the data and create that many div objects with longUrl and shortUrl objects in it. Also when database will be updated new div object should be created, and when I delete database information all the div elements should be deleted too, is this possible to do?
You should be using a templating engine for this the two most popular ones for Node.js are pug(formerly Jade) and hbs(Handlebars.js).
There are a lot of other template engines here you could consider.
I am not exactly sure how to go about using/accessing the data requested from a discord oauth2 authentication. I have requested to access the guilds the user is in and the username and avatar of the user. I get a successful authentication, but my question is how do i use and access that data? This is my code currently:
server.js
const express = require('express');
const path = require('path');
const app = express();
app.use('/static', express.static(path.join(__dirname, 'static')));
app.get('/', (req, res) => {
res.status(200).sendFile(path.join(__dirname, 'index.html'));
});
app.listen(50451, () => {
console.info('Running on port 50451');
});
app.use('/api/discord', require('./api/discord'));
app.use((err, req, res, next) => {
switch (err.message) {
case 'NoCodeProvided':
return res.status(400).send({
status: 'ERROR',
error: err.message,
});
default:
return res.status(500).send({
status: 'ERROR',
error: err.message,
});
}
});
discord.js
const express = require('express');
const dotenv = require('dotenv').config()
const fetch = require('node-fetch');
const btoa = require('btoa');
const { catchAsync } = require('../utils');
const router = express.Router();
const scopes = ['identify', 'guilds'];
const CLIENT_ID = process.env.CLIENT_ID;
const CLIENT_SECRET = process.env.CLIENT_SECRET;
const redirect =
encodeURIComponent('http://localhost:50451/api/discord/callback');
router.get('/login', (req, res) => {
res.redirect(`https://discordapp.com/api/oauth2/authorize?client_id=${CLIENT_ID}&redirect_uri=${redirect}&response_type=code&scope=identify%20guilds`);
});
router.get('/callback', catchAsync(async (req, res) => {
if (!req.query.code) throw new Error('NoCodeProvided');
const code = req.query.code;
const creds = btoa(`${CLIENT_ID}:${CLIENT_SECRET}`);
const response = await fetch(`https://discordapp.com/api/oauth2/token?grant_type=authorization_code&code=${code}&redirect_uri=${redirect}`,
{
method: 'POST',
headers: {
Authorization: `Basic ${creds}`,
},
});
const json = await response.json();
res.redirect(`/success/?token=${json.access_token}`);
}));
module.exports = router;
Any help will be greatly appreciated. Thanks!
It's almost the same as the way you use the req.query.code to get the access_token.
const fetchDiscordUserInfo = await fetch('http://discordapp.com/api/users/#me', {
headers: {
Authorization: `Bearer ${json.access_token}`,
}
});
const userInfo = await fetchDiscordUserInfo.json();
yourUserId = `${userInfo.id}`;
yourUserName = `${userInfo.username}`;
// or simply...
console.log(userInfo);