So i have found an api for node https://github.com/schme16/node-mangafox
But i have no idea on how to use it
Lets say that i want to use this
mangaFox.getManga = function(callback){
$.get('http://mangafox.me/manga/',function(data){
var list = {};
data.find('.manga_list li a').each(function(index, d){
var b = $(d);
list[mangaFox.fixTitle(b.text())] = {id:b.attr('rel'), title:b.text()};
});
(callback||function(){})(list);
}, true);
}
What should i do to show the list in the '/' route
This i what i have so far
var express = require('express'),
path = require('path'),
mangaFox = require('node-mangafox');
var app = express();
app.get('/', function(req, res) {
});
app.listen(1337);
console.log('oke');
If some cloud help me understand how this works
app.get('/', function(req, res) {
function renderList(data) {
return Object.keys(data);
res.send(JSON.stringify(list));
}
var list = mangaFox.getManga(renderList);
});
This is the simplest thing I can come up with. You just get the object returned by the module, list its keys, and send back that stringified as your response. Try it out. You'll probably want to replace the renderList with some HTML templating.
Related
I have an array that is initialized when my user makes an input. I want that array to be passed to the nodeJS side of things rather than just stick around in the frontend. All the other variables that I am grabbing are named "net[object]" so I can grab them all in an array when necessary. The array I created only ever has one element being displayed in an input group at a time. If you need a better visual, go to "#nodes in hidden layer" for the neural net demo here: http://irisml.org/demos/
I am a complete noob when it comes to web development, so please be patient with me :)
//JS code creating array
numLayers.addEventListener('input', function(){
nodesArray.length = 0
num = numLayers.value;
nodes.innerHTML = '';
initialized = true;
for(var i = 1; i < num - 1; i++){
var node = document.createElement("option");
var textnode = document.createTextNode("Nodes in Hidden Layer " + i);
node.appendChild(textnode);
document.getElementById("nodes").appendChild(node);
nodesArray.push(1)
}
});
//Current NodeJS code
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
router.post('/', function(req, res){
console.log(req.body.net)
});
You can use "fetch" to send a post request to the backend.
//frontend
let nodesArray = [1,2,3];
let body = JSON.stringify({net:nodesArray});
fetch("/",
{method:"post",
body:body,
headers: {
'Content-Type': 'application/json'
}});
Your backend needs to listen on a port
//backend
var express = require('express');
var app = new express();
app.use(express.json())
app.listen(3000, console.error); //listen on port http://localhost:3000
app.use('/static', express.static(__dirname + '/static')); //OPTIONAL host static/index.html
app.post('/', function(req, res){
console.log(req.body.net, 'net');
res.send("RESPONSE");
});
I'm trying to learn Socket.io and I'm a beginner in NodeJS.
I'm using JSON object as a kind of key-value store for mapping callback function with relevant event names. May be there is some other alternative to do it efficiently which I don't know. The problem is in the code below, when I call bob.printName() it prints the JSON object perfectly. But when I call the same function using the callbacks['connection'](), it says the JSON object is undefined. I would like to know the reason of that and also love to know any other efficient alternatives like PHP like array indexing.
/***
** index.js
***/
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var User = require('./User');
var bob = new User();
var callbacks = {
'connection': bob.printName
};
io.on('connection', function(socket){
bob.printName();
callbacks['connection']();
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
/***
** User.js
***/
var jsonObj = null;
function User() {
this.jsonObj = {
type: 'type',
body: 'body'
};
}
User.prototype.printName = function(){
console.log(this.jsonObj);
}
module.exports = User;
I'd like to have some advice on how to call different database queries based on the path in the url using express.js. Here's a working example code but I'm not sure if that is the good way of doing it:
server.js
var express = require('express'),
app = express(),
Promise = require("bluebird"),
db = require('./db/managedb'); // database modules for sequelize.js
app.get('/p/:section/:optional?', function(req, res){
var section = req.params["section"];
var optional = req.params["optional"];
if(section == "index"){
Promise.props({
main: db.db.query('CALL sp1()'),
second: db.db.query("CALL sp2()")
}).then(function(obj){
res.render(section+'.html',obj)
}).catch(function (error) {
})
}else if(section == "overviews"){
var page = req.query.page || 0;
Promise.resolve(db.db.query('CALL sp3(:page)',{page:page})).then(function(d){
res.render(section+'.html',d)
})
}else if(section == "reviews"){
var page = req.query.page || 0;
var review_id = req.query.review_id || 1;
Promise.resolve(db.db.query('CALL sp4(:review_id,:page)',{review_id:review_id,page:page})).then(function(d){
res.render(section+'.html',d)
})
}
})
Is it an okay solution? My concern is that if I kept adding more conditions for new sections, it might be quite messy, but is there a better way to call different database queries based on the path? Any suggestion is appreciated.
I would simply use different routing handlers, like this:
var express = require('express'),
app = express(),
Promise = require('bluebird'),
db = require('./db/managedb'); // database modules for sequelize.js
app.get('/p/index/:optional?', function(req, res) {
Promise.props({
main: db.db.query('CALL sp1()'),
second: db.db.query('CALL sp2()')
}).then(function(obj) {
res.render('index.html', obj);
}).catch(function(error) {
});
});
app.get('/p/overviews/:optional?', function(req, res) {
var page = req.query.page || 0;
Promise.resolve(db.db.query('CALL sp3(:page)', {page: page})).then(function(d) {
res.render('overviews.html', d);
});
});
app.get('/p/reviews/:optional?', function(req, res) {
var page = req.query.page || 0;
var review_id = req.query.review_id || 1;
Promise.resolve(db.db.query('CALL sp4(:review_id,:page)', {review_id: review_id, page: page})).then(function(d) {
res.render('reviews.html', d);
});
});
If you have more shared code between the routes, you could use multiple routing handlers using next() callbacks. For example, you could write your content from d somewhere into req and then just call next() instead of res.render(…). You then add another routing handler with the same signature as your old one (matching all routes) below those three and call res.render(section + '.html', req.d) (or other code) in there.
I have put the server setting script into a separate js file called server.js. My problem is that I don't know how to get the value of cookie_key from the express middleware function and pass it back to the index.js file.
server.js:
var express = require('express'),
app = express(),
http = require('http').createServer(app),
cookie = cookieParser = require('cookie-parser'),
url = require('url');
module.exports = {
use_app : function(){
app.use(function (req, res, next) {
var cacheTime = 86400000*7; // 7 days
if (!res.getHeader('Cache-Control'))
res.setHeader('Cache-Control', 'public, max-age=' + (cacheTime / 1000));
next();
});
},
get_app : function(callback){
app.use(cookieParser());
app.get('/id/:tagId', function(req, res){ // parse the url parameter to get the file name
function getkey(err,data){ // get users' session cookie
var cookie_key;
if(err)
{
callback(err);
}
cookie_key = req.cookies["session"];
callback(cookie_key);
}
var filename = req.param("tagId");
res.sendFile(filename+'.html');
});
}
}
index.js:
var server = require('./server'),
server.use_app();
server.get_app(); // how to get the cookie_key when calling this function?
console.log(show_cookie_key_from the module);
if(cookie_key !== undefined)
{
// do something
}
I tried to write a callback function to fetch the cookie key but I don't think it's working.
Update from A.B's answer:
var server = require('./server');
server.use_app();
server.get_app(function(cookie){
if(cookie !== undefined)
{
// do something
}
});
But I still think there is something strange about this setup, what exactly are you trying to accomplish with splitting the app up like this?
Since you are using callback function and that is being poplulated with cookie value , you can get this like following:
var server = require('./server');
server.use_app();
server.get_app(function(cookie){
cookie_key= cookie
if(cookie_key !== undefined)
{
// do something
}
});
If you had a server js like so:
var app = require('express'),
http = require('http'),
news = require('./server/api/news'),
db = require('mongoose');
/* app config..... */
app.get('/api/news', news.list);
var server = http.createServer(app);
server.listen(app.get('port'), function () {
console.log("Server running");
});
And I wanted to create an API to handle adding news items to the database:
var db = require('mongoose');
/*** Public Interfaces ***/
function list(req, res) {
var offset = ~~req.query.offset || 0,
limit = ~~req.query.limit || 25;
db.News.find(function (err, newsItems) {
res.json(newsItems.slice(offset*limit, offset*limit + limit));
});
}
exports.list = list;
This API would exist in its own file, how do I use the instance of the db created in the server.js inside the new module.
Or do you create and open a new connection each time you query the database?
Thanks
I would probably do it more like this
the server :
var express = require('express'),
app = express(),
http = require('http'),
db = require('mongoose'),
news = require('./server/api/news')(db); // you can pass anything as args
app.get('/api/news', news.list);
/* add routes here, or use a file for the routes */
// app.get('/api/morenews', news.more_news); .... etc
http.createServer(app).listen(8000);
and in the ../news/index.js file or whatever you're using, I'd use a literal, but you can always use exports to pass back each method as well
module.exports = function(db) {
/* now db is always accessible within this scope */
return {
list : function (req, res) {
var offset = ~~req.query.offset || 0,
limit = ~~req.query.limit || 25;
db.News.find(function (err, newsItems) {
res.json(newsItems.slice(offset*limit, offset*limit + limit));
});
}, // now you can easily add more properties
more_news : function(req, res) {
res.end('Hello kitty');
}
}
}