I have this code.This is one file.
function success2(data) {
alert(data);
}
function addButton(){
alert("adding " + $("#topic").val());
$.post("/add",{topic:$("#topic").val()},success2);
return false;
}
function getButton(){
alert("Geting " + $("#topic").val());
$.get("/gettopic",{topic:$("#topic").val()},success2);
return false;
}
$(document).ready(function(){
$("#addButton").click(addButton);
$("#getButton").click(getButton);
});
This is in a separate file.
var express = require('express');
var router = express.Router();
router.get("/",function(request,response){
response.sendFile(__dirname + "/public/views/index.html");
});
var data = [];
router.post('/add', function(req,res){
data.push(req.body.topic);
res.json(req.body.topic);
});
router.get('/gettopic', function(req,res){
let result = req.query.topic
res.json(result;
});
function getTopic(name){
for(let i = 0;i<data.length){
if(name == data[i])
return data[i];
}
return null;
}
module.exports = router;
And here is the main file.
var express = require('express');
var bodyParser = require('body-parser'); //new
var routes = require("./routes");
var app = express();
app.use(bodyParser.urlencoded({ extended: true })); //new
app.use(bodyParser.json()); //new
app.use('/', express.static('./'));
app.use('/js', express.static('./public/js'));
app.use(routes);
app.listen(3000);
When I send the "gettopic" GET request it throws a 404 error "GET http://localhost:3000/gettopic?topic=sdfsd 404 (Not Found)". I was also experiencing this error with POST requests but after re-writng the code many times, some of the request now work and I have no idea what I did differently.
Related
const express = require('express');
const app = express();
const port = 3000;
const bodyPar=require('body-parser');
const session = require('express-session');
const path=require('path');
var user=["Jared","Bill","Jason","Jeremy"];
app.use(express.static('proiect'));
app.use(bodyPar.urlencoded({extended : true}));
app.use(bodyPar.json());
app.use(session({secret:'secret',saveUninitialized:true,resave:true}));
var sess;
var s;
app.post('/login',function(req,res){
var i=0;
sess=req.session;
var username=req.body.username;
var pass=req.body.password;
var but=req.body.value;
s=0;
sess.email=username;
for(i=0;i<3;i++)
{
if(username==user[i])
{
s=s+1;
i=5;
}
}
if(pass="123")
s=s+1;
if(s==2)
res.redirect('homepage.html');
else
res.redirect('login-error.html');
res.end();
});
app.get('/homepage.html',function(req,res){
console.log('aaa');
});
app.get('bios.html',function(req,res){
console.log('aaa');
});
app.post('/guest',function(req,res){
sess=req.session;
sess.username="Guest";
s=2;
res.redirect('homepage.html');
});
app.get('/logout',function(req,res){
req.session.destroy(function(){
res.redirect('login.html');
s=0;
});
});
app.listen(port, () => console.log(`listening on port ${port}!`));
The server doesnt handle the app.get('homepage.html') or 'bios.html' it just displays the html file in the browser.(should hang and display smth on console).
Am i supposed to serve/render those files instead of directly accessing them in the browser?
Both of those files are in the /proiect/ folder i've included on the server.
Express finds the static HTML file and then returns that to the user. Therefore it skips the route handler you wrote.
If you are trying to perform some server-side logic and returning an HTML page, rather return the page inside your route handler to avoid such side effects. In this case, create your HTML file in a templates folder or something. Then you can put all your static resources in your static folder. So your structure would look something like this:
+ project_folder
+ static
+ css
- style.css
+ js
- app.js
+ templates
- bios.html
- homepage.html
- login.html
- login-error.html
- app.js
Then your app.js would look something like this:
const express = require('express');
const app = express();
const port = 3000;
const bodyPar=require('body-parser');
const session = require('express-session');
const path=require('path');
var user=["Jared","Bill","Jason","Jeremy"];
app.use(express.static('static'));
app.use(bodyPar.urlencoded({extended : true}));
app.use(bodyPar.json());
app.use(session({secret:'secret',saveUninitialized:true,resave:true}));
var sess;
var s;
app.get('/login', function(req, res) {
res.sendFile(path.join(__dirname, '/templates/login.html'));
});
app.post('/login',function(req,res){
var i=0;
sess=req.session;
var username=req.body.username;
var pass=req.body.password;
var but=req.body.value;
s=0;
sess.email=username;
for(i=0;i<3;i++)
{
if(username==user[i])
{
s=s+1;
i=5;
}
}
if(pass="123")
s=s+1;
if(s==2)
res.redirect('homepage');
else
res.redirect('login-error');
res.end();
});
app.get('/homepage',function(req,res){
res.sendFile(path.join(__dirname, '/templates/homepage.html'));
});
app.get('bios',function(req,res){
res.sendFile(path.join(__dirname, '/templates/bios.html'));
});
app.get('login-error', function(req, res) {
res.sendFile(path.join(__dirname, '/templates/login-error.html'));
});
app.post('/guest',function(req,res){
sess=req.session;
sess.username="Guest";
s=2;
res.redirect('homepage');
});
app.get('/logout',function(req,res){
req.session.destroy(function(){
res.redirect('login');
s=0;
});
});
app.listen(port, () => console.log(`listening on port ${port}!`));
I have a JS file in a folder called public, which also has my CSS file in it. I'm trying to access a function from the JS file (scripts.js), but am having no luck. I've followed this post (amongst others), but I am still getting an error of Error: Cannot find module './scripts.js'. If anyone can help me out, that would be great.
app.js
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var request = require("request");
var scripts = require("/scripts.js");
app.use(bodyParser.urlencoded({extended: true}));
app.set("view engine", "ejs");
app.use(express.static(__dirname + '/public'));
const apiUrl = "https://api.darksky.net/forecast/";
const apiKey = "XXX";
app.get('/', function(req, res){
res.render("index");
});
app.post('/results', function(req, res){
var lat = req.body.latitude;
var long = req.body.longitude;
request(apiUrl + apiKey + "/" + long + "," + lat, function(error, response, body){
if (!error && response.statusCode == 200) {
var data = JSON.parse(body);
var temperature = scripts.converter(data.currently.temperature)
res.render("results", {data: data, temperature: temperature})
} else {
console.log(response.body);
}
});
});
app.get('/results', function(req, res){
res.render("results");
});
app.listen(3000, function(){
console.log("Server has started");
})
scripts.js
module.converter = function(cel) {
var cel = (far - 32) * (5/9);
return cel;
}
exports.data = module;
The path to your module is wrong.
Try var scripts = require("./public/scripts.js"); instead.
You are loading /scripts.js, which is a scripts.js file located at your computers root. To load a file in the current directory, you would do ./scripts.js. In a directory above the current one, it would be ../scripts.js.
If the file is in a directory below the current directory, like in your case, it would be './directoryname/scripts.js'. directoryname being public in your case
Stuck on my first attempt at a basic app. Scraper.js scrapes a URL and writes the returned array to the document obj when run alone in console, so that part works. Now all I want is an Express server to run the script whenever I open localhost:3000 but not sure how to do so.
|node_modules
|package.json
|public
|-index.html (boilerplate HTML. Not importing anything)
|src
|-scraper.js
|index.js
index.js:
var scraperjs = require('scraperjs');
var express = require('express');
var app = express()
app.use(express.static(__dirname + '/public'));
app.listen(3000);
--
scraper.js:
scraperjs.StaticScraper.create('https://examplesite.com/')
.scrape(function($) {
return $(".entry-content p").map(function() {
var content = $(this).html();
return content
}
}).get();
})
.then(function(data) {
... // eventually will write the items returned from the data array to div's
}
});
You need to export the scraperjs function using module.exports = functionName() as the last line in scraper.js.
Your require in index.js needs to factor in the path location for scraper.js. So:
var scraperjs = require('./src/scraperjs');
Here is a one that i've coded with promises, and also using a global variable which is daNews
var scraperjs = require('scraperjs');
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
var url = 'https://news.ycombinator.com/';
var daNews;
function myScraper(){
return new Promise((resolve, reject) => {
scraperjs.StaticScraper.create(url)
.scrape(function($) {
return $(".title a").map(function() {
return $(this).text();
}).get();
})
.then(function(news) {
daNews = news;
resolve('done');
})
});
}
app.get('/', function(req, res){
async function m1(){
var x = await myScraper();
if(x == 'done'){
res.send(daNews);
}else{
console.log('err');
}
}
m1();
})
app.listen(3000);
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
//PROBLEM LINE
**app.use(parser.json);**
///////////////
var todos = [];
var nextTodoItem = 1;
app.use(bodyParser.json);
app.get('/', function(req, res){
//console.log("ToDo Root");
res.send("ToDo Root");
});
//GET REQUEST TO GET ALL TODO ITEMS
// GET /todos
app.get('/todos', function (req, res) {
// Need to send back the array of todos
res.json(todos); //array is converted to JSON.
}
);
//GET REQUEST TO GET SOME SPECIFIC TODO
//GET todos/:id
//Express uses : (colon) to parse data.
app.get('/todos/:id', function (req, res) {
var todoID = parseInt(req.params.id, 10);
var todoObjectWithID = -1;
todos.forEach(function (todo) {
if(todo.id == todoID){
todoObjectWithID = todos[todoID - 1];
}
});
if(todoObjectWithID == -1){
res.status(404).send();
} else {
res.json(todoObjectWithID); //Send the JSON of the specific todo with id requested.
}
console.log('Asing for todo with id of ' + req.params.id);
});
//Create a POST request to create new TODO Items.
//POST /todos
app.post('/todos', function(req, res){
var body = req.body;
console.log("description");
res.json(body);
});
//Server basic start up (port and log)
app.listen(3000, function () {
console.log("Server up and running");
});
I run the server with bash (Mac OS) but I go to http://localhost:3000 nothing loads, but when I remove the app.use(bodyParser) it loads properly.
What is the problem in the body-parser?
This problem only occurs when I have that line, otherwise, the server runs up perfectly fine. I need that parser though, so what is my option?
Change that line to app.use(bodyParser.json());
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
}
});