i'm trying to do a little website like sickgearr for my seedbox :
i want a search form which will send a search query to my torrent providers using this api : https://github.com/JimmyLaurent/torrent-search-api
i managed getting text from the form, making the api calls and get results printed in the console.
but when i try to pass them to the soon to-become result page, i'm only passing promises and i don't quite understand the principle of promises.
If someone could help me resolve my issues i'd be really really gratefull or atleast give me some hints !
Here is my code made up from several ejs, nodejs begginers tutorials :
const express = require('express');
const bodyParser = require('body-parser');
const app = express()
const TorrentSearchApi = require('torrent-search-api');
const tableify = require('tableify');
TorrentSearchApi.enableProvider('Yggtorrent','Login', 'Password');
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs')
async function search(query){ // Search for torrents using the api
var string = query.toLowerCase();
//console.log(string);
const torrents = await TorrentSearchApi.search(string,'All',20); // Search for legal linux distros
return(JSON.stringify(torrents));
}
app.get('/', function (req, res) {
res.render('index');
})
app.post('/', function (req, res) {
var rawTorrent = search(req.body.torrent);
var page = tableify(rawTorrent); //printing rawtorrent will only give me "promise"
res.render('results',page);
})
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
Your search function is using async/await.
It means the search function is asynchrone and returns a Promise.
You should await its result (line 23).
https://javascript.info/async-await
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const TorrentSearchApi = require('torrent-search-api')
const tableify = require('tableify')
TorrentSearchApi.enableProvider('Yggtorrent','Login', 'Password')
app.use(express.static('public'))
app.use(bodyParser.urlencoded({ extended: true }))
app.set('view engine', 'ejs')
const search = async query => {
const loweredQuery = query.toLowerCase()
const torrents = await TorrentSearchApi.search(loweredQuery, 'All', 20)
return JSON.stringify(torrents)
}
app.get('/', (_, res) => res.render('index'))
app.post('/', async (req, res) => {
const torrents = await search(req.body.torrent) // Right here
const htmlTable = tableify(torrents)
res.render('results', htmlTable)
})
app.listen(3000, function () {
console.log('Example app listening on port 3000!')
})
Related
i created variable in app.post, and i want to use it in app.get, but before this i added this one to my database, but i don't know how to get access to this variable in other function, here is my code
const express = require("express");
const { default: mongoose } = require("mongoose");
const app = express();
const port = 3000;
const Task = require(`./models/task`);
require("./db/moongose");
// sendFile will go here
app.set("view engine", "ejs");
app.use(express.static("public"));
app.use(express.urlencoded({ extended: false }));
app.get("/task", (req, res) => {
res.render("../public/mainPage.ejs", {tasks: mongoose});
});
app.post("/task", async (req, res) => {
const task = new Task({
description: req.body.task,
});
try {
await task.save();
console.log(task.description);
res.redirect("/task");
} catch (e) {}
});
app.listen(port);
console.log("Server started at http://localhost:" + port);
and all i want to do is get acces to task.description in app.get
I'm trying to recreate a Note Taking App using Express. My code follows the instructor's example but when I deploy it and try to add a new note I get the error cannot get/api/name...I am not sure what I am doing wrong.
enter code here
const fs = require('fs');
const path = require ('path');
const express = require('express');
const dbJson = require('./db/db.json')
const {v1 : uuidv1} = require('uuid');
const PORT = process.env.PORT || 3001;
const app = express();
app.use(express.urlencoded({extended: true}));
app.use(express.json());
app.use(express.static("public"));
app.get('/notes', (req, res) => {
res.sendFile(path.join(__dirname, './public/notes.html'));
});
app.get('/api/notes', (req,res) => {
const dataNotes = fs.readFileSync(path.join(__dirname, './db/db.json'), "utf-8");
const parseNotes = JSON.parse(dataNotes);
res.json(parseNotes);
});
Add at the end: app.listen(PORT);
That will work. The problem was that you didn't start the server
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))
})
I've created simple Express.js Rest API with MongoDB. I am using this package: https://www.npmjs.com/package/api-query-params and everything works very well except for one thing. I have a URL like this:
localhost/properties/?town=LONDON
this returns all properties from London, the problem is with this is the next thing, I need to put capitalize value (LONDON), I am trying to achieve that this value can be lowercase (london), so final URL will be like this:
localhost/properties/?town=london
My route:
const express = require('express');
const router = express.Router();
const Property = require('../models/Property');
const aqp = require ('api-query-params');
router.get('/all', (req, res, next) => {
const { filter, skip, limit, sort, projection, population, casters } = aqp(req.query, {
casters: {
lowercase: val => req.query.toLowerCase(),
},
});
Property.find(filter)
.skip(skip)
.limit(limit)
.sort(sort)
.select(projection)
.populate(population)
.exec((err, properties) => {
if (err) {
return next(err);
}
res.send(properties);
});
});
module.exports = router;
And app.js
const express = require('express');
const app = express();
const bodyParser = require("body-parser");
require('dotenv/config');
const mongoose = require('mongoose');
const propertyRoute = require('./routes/property');
const PORT = process.env.PORT || 3000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use('/properties', propertyRoute);
//routes
app.get('/', (req, res) => {
res.send('value');
});
mongoose.connect('linkdatabse', {
newUrlParser: true,
})
app.listen(PORT, () => {
console.log(`Server started on port ${PORT}`);
});
I've updated my route according to documentation: https://www.npmjs.com/package/api-query-params#add-custom-casting-functions
but still, this doesn't work
Can anybody try to help me with this, what am I doing wrong?
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);
});