In the file where I have written the request methods looks like this:
article.js
router
.route("/")
.all((req, res) => {
console.log("this should happen for any call to the article route");
})
.get((req, res) => {
// returns all the data in the database
Rest.find({}, (err, result) => {
if (!err) {
console.log(result);
res.send(result);
} else {
res.send(err);
}
});
})
.post((req, res) => {
const articleTitle = req.body.title;
const articleContent = req.body.content;
const articleDate = req.body.date;
const article = new Rest({
title: articleTitle,
content: articleContent,
date: articleDate,
});
article
.save()
.then((result) => {
res.send(result);
})
.catch((err) => {
res.send(err);
});
})
.delete((req, res) => {
Rest.deleteMany({}, (err, result) => {
if (!err) {
res.send(result);
} else {
res.send(err);
}
});
});
module.exports = router;
and I have and app.js
const article = require("./article");
app.use('/articles', article);
When I make a call to url it just loads and I get no response.
At first I was just writing it http verb on it own. But it was making my app.js have a lot of code so I decided to move all this logic to its own file article.js and use router.route() to chain the http verbs together to make the code look cleaner. But doing that I encounter the error when I get no result and it just loads forever.
Am I doing something wrong?
Any help is appreciated thanks.
I figured it out. The solution was to add next() to .all() method. Because I was passing next, I think the http request was just stuck at that point waiting.
So the new code should be
router
.route('/')
.all((req, res, next)) => {
// logic
next();
})
and the rest of the code follows.
Related
I would like to get the data from session variable (req.user.username) then use it for posting. I'm using passportjs as authentication. I'm using router. Here is my code:
router.use('/login', passport.authenticate("local-register", async (err, user, info) => {
if (err) {
return next('Error');
}
if (!user) {
return next('Error');
}
req.user = user;
return req.login(user, (error: Error) => {
if (error) {
return next('Error');
}
return req.session.save((erro: Error) => {
if (erro) {
return next('Error');
}
return next();
});
});
})(req, res, next);)
router.get('/', async (req, res) => {
console.log(req.user.username) // working just fine
});
router.post('/upload', async (req, res) => {
const uploaderName = req.user.username // I'm getting undefined
const upload = await database.query('INSERT INTO user WHERE username=$1', [uploaderName])
console.log(uploaderName);
})
So I finally found the answer to the question. For those who will encounter the problem in the future. You just add the session middleware AGAIN on the top of the routes. If your routes are separated to the main server file.
/src/routes/routes.ts -> add again the middleware on top.
const app = router();
app.use(sessions) // -> right here you need to add the middleware again to //access the req.user session variable
app.get('/', async (req, res) => {
console.log(req.user.username) // working just fine
});
app.post('/upload', async (req, res) => {
const uploaderName = req.user.username // I'm getting undefined
const upload = await database.query('INSERT INTO user WHERE username=$1', [uploaderName])
console.log(uploaderName);
})
UPDATE: I it checks for /:slug even if i go to a different route, i think thats causing the problem.
I'm trying to create a URL Shortener with Nodejs, Expressjs, MongoDB and EJS.
Even though my application is working perfectly, I keep getting this error in terminal:
My routes :
const express = require("express");
const URLs = require("../models/urls");
const { findById, find } = require("../models/urls");
const router = express.Router();
router.get("/", (req, res) => {
res.render("index", { shortUrl: new URLs() });
});
router.post("/redirect", (req, res) => {
let url = req.body.url;
let slug = req.body.slug;
let shortenUrl = new URLs({
url: url,
slug: slug,
});
shortenUrl.save();
res.render("shortenUrl", { shortenUrl });
});
router.get("/about", (req, res) => {
res.render("about");
});
router.get("/contact", (req, res) => {
res.render("contact");
});
router.get("/all", async (req, res) => {
try {
var shortUrls = await URLs.find({});
res.render("all", { shortUrls });
} catch (error) {
console.log(error);
}
});
//:TODO
router.get("/:slug", async (req, res) => {
var shortUrl = await URLs.findOne({ slug: req.params.slug }).exec();
try {
console.log(shortUrl);
var urls = await shortUrl.url;
if (urls.includes("http", 0)) {
return res.redirect(urls);
} else {
return res.redirect(`http://${urls}`);
}
} catch (error) {
console.log(error);
}
});
module.exports = router;
I didn't get this error until I made API for the app (in separate routes file).
Also in my server I'm using:
app.use(bodyParser.urlencoded({ extended: false }));
and using:
app.use(express.json());
doesn't help either.
Any help would be appreciated, Thank you c:
I added an if statement to the route and that solved the problem, thanks to #Pukka c:
router.get("/:slug", async (req, res) => {
var shortUrl = await URLs.findOne({ slug: req.params.slug }).exec();
if (shortUrl) {
try {
console.log(shortUrl);
var urls = await shortUrl.url;
if (urls.includes("http", 0)) {
return res.redirect(urls);
} else {
return res.redirect(`http://${urls}`);
}
} catch (error) {
console.log(error);
}
}
I have a problem right now that I can't solve by myself. I assume you know more here. I'm just getting started.
By using the following code I'm getting a list of customers:
app.get("/customers", customers.findAll);
I wanted to add authentication. But now I don't know how to execute "customers.findAll" and get the value as JSON.
app.get("/customers", verifyToken, (req, res) => {
jwt.verify(req.token, 'justAtest, (err, authData) => {
if (err) {
res.sendStatus(403);
} else {
// execute customers.findAll
}
});
});
Customers is integrated via a requirement
const customers = require("../controllers/customer.controller.js");
The contents are as follows:
exports.findAll = (req, res) => {
Customer.getAll((err, data) => {
if (err)
res.status(500).send({
message:
err.message || "Some error occurred while retrieving customers."
});
else res.send(data);
});
};
Do you have any ideas?
Thank you in advance.
Grettings
Rok
You achieve that using something called "middleware". Explore it since it is very important.
Basically :
app.get("/customers", verifyToken,customers.findAll);
Wherre verify token is a funtion that has 3 parameters: req, res and 3rd one called "next".
So your verify token function would look something like:
(req, res,next) => {
jwt.verify(req.token, 'justAtest, (err, authData) => {
if (err) {
res.sendStatus(403);
} else {
next();
}
});
}
I took it from your snippet. Basically if you want to jump to customeeers.finalAll, just call "next" and it jumps to next function :D.
i am new to node.js and want to create api for getting data and update that data on frontend,please give me solution for this,i am getting data from this code but unable to update data.I am using react js for frontend.
var express = require("express");
var app = express();
var oracledb = require('oracledb');
var dbconfig= require('./dbconfig')
(async function () {
let connection
try {
connection = await oracledb.getConnection({
user: 'dbconfig.user',
password: 'dbconfig.password',
connectString: 'dbconfig.connectstring'
});
var result = await connection.execute('select * from
PROPERTY.app_booklet_challan_detail', []);
console.log("Successfully connected to Oracle!")
console.log(result)
} catch (err) {
console.log("Error: ", err);
} finally {
if (connection) {
try {
await connection.close()
} catch (err) {
console.log("Error when executing the database connection: ", err);
}
}
}
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')
next();
});
app.get('/list', (req, res, next) => {
res.send(result);
next()
});
app.put('/list/update', (req, res, next) => {
let STATUS=res.data
connection.execute('UPDATE PROPERTY.app_booklet_challan_detail SET STATUS= ? WHERE
BOOKLETID= ? ', [STATUS])
res.send(STATUS)
next()
})
app.listen(3001, function () {
console.log("Started on PORT 3001");
})
})()
Your question is a little broad to answer with code, but I've written an entire series on this topic: https://jsao.io/2018/03/creating-a-rest-api-with-node-js-and-oracle-database/
Note there are links to a GitHub repo with the code from each module.
Once you finish with the series you should be able to take things in the direction that makes the most sense for your project.
I am serving a static webpage from Node.JS via Express webserver:
app.use('/', express.static('public'));
What is the most minimalistic way to integrate some dynamic content, e.g. a list of items that is retrieved from a database into such a page?
I see the possibility to "fake" a .js file on the server that is actually dynamically created and then loaded in an index.html that resides inside the public folder on the server:
app.get('/myScript.js', (req, res) => {
data = getDataFromDatabase();
res.send('var data1 = ' + data[0] + '; var data2 = ' + data[1]);
});
This seems extremely hacky and I wonder what the best minimalistic approach to this is.
You can also return a response from a callback inside of your get route. I do something like this:
Endpoint:
router.get('/people', (req, res) => {
People.list((error, response) => {
if (error) return res.end();
return res.send(response);
});
});
Model:
module.exports = {
connect: (callback) => {
r.connect({
host: config.db.host,
port: config.db.port,
db: config.db.name
})
.then((connection) => {
return callback(null, connection);
})
.error((err) => {
return callback(err);
});
},
list: function (callback) {
this.connect((err, connection) => {
if (err) return callback(err);
r.db(config.db.name).table(config.db.tables.people)
.run(connection)
.then((cursor) => {
return cursor.toArray();
})
.then((users) => {
return callback(null, users);
})
.error((err) => {
return callback(err);
});
});
},
...
With this then I get the response object printed to my screen. The model code is rethinkdb code, but you can substitute that with whatever you are using. Sorry if this wasn't quite what you were after. Best of luck with your build =)