Whe aren't my subpages visible with nodejs? - html

I am making simple node app for my website.
I've configured my app.js, controllers and routers so far.
My problem is I keep getting error 404 on two from three subpages, index works fine also. I think they're pretty much the same construction-wise, I've tried tracing app-route-controller but seems good to me.
My console output:
GET / 304 1.443 ms - -
GET /css/style.css 304 0.325 ms - -
GET /images/IMG_2202.png 304 0.639 ms - -
GET /images/vertabelo-tabele.png 304 0.774 ms - -
GET /sprzet 200 1.904 ms - 3241
GET /css/style.css 304 0.393 ms - -
GET /images/IMG_2202.png 304 0.501 ms - -
GET /zamowienia 404 1.152 ms - 1393
GET /wysylka 404 0.917 ms - 1393
As you can see /zamowienia and /wysylka are not found. However the structure is the same as for sprzet.
My app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
const sprzetRouter = require('./routes/sprzetRoute');
const wysylkaRouter = require('./routes/wysylkaRoute');
const zamowieniaRouter = require('./routes/zamowieniaRoute');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/sprzet', sprzetRouter);
app.use('/list-wys', wysylkaRouter);
app.use('/list', zamowieniaRouter);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
wysylkaRoute
const express = require('express');
const router = express.Router();
const wysylkaController = require('../controllers/wysylkaController');
router.get('/', wysylkaController.showWysylkaList);
router.get('/add', wysylkaController.showAddWysylkaForm);
router.get('/details/:wysId', wysylkaController.showWysylkaDetails);
module.exports = router;
and wysylkaController
const { Router } = require("express");
exports.showWysylkaList = (req, res, next) => {
res.render('pages/wysylka/list-wys', {
navLocation: 'wys'
});
}
exports.showAddWysylkaForm = (req, res, next) => {
res.render('pages/wysylka/form-wys', {
navLocation: 'wys'
});
}
exports.showWysylkaDetails = (req, res, next) => {
res.render('pages/wysylka/list-wys-details', {
navLocation: 'wys'
});
}
My nav also seems fine:
<nav>
<ul>
<li>Strona główna</li>
<li>Zamówienia</li>
<li>Sprzęt</li>
<li>Wysylka</li>
</ul>
</nav>
I've tried backtracing all my paths and comparing /wysylka and /zamowienia to /sprzet but they all seem built the same way.

The problem were wrong endpoints in the app.js.
I had to switch this:
app.use('/', indexRouter);
app.use('/sprzet', sprzetRouter);
app.use('/list-wys', wysylkaRouter);
app.use('/list', zamowieniaRouter);
To this:
app.use('/', indexRouter);
app.use('/sprzet', sprzetRouter);
app.use('/wysylka', wysylkaRouter);
app.use('/zamowienia', zamowieniaRouter);
For endpoints to point to the subfolders instead of specific files.

Related

Why Does My req.body Return Empty on Express

I can't understand why I'm getting an empty req.body {} in client side I get undefined or when I try to use payload = req.body.payload and console.log(payload) I get undefined on the server side and on the client side I get (chrome developer tool console)
ERROR TypeError: Cannot read properties of null (reading 'payload').
What I don't understand is the server receives the request payload(status 201) the response payload is empty, also correct me if I'm wrong the response is a JavaScript object and in the service the original payload is contained so shouldn't I get that in the response.
I have looked at many topics that have the same issue. I'm already doing things that fixed some of the issues.
I have a Content-Type application/json, I apply the app.use(json()) before I use my routes, which seemed to have been the problem with some. Yet I still get empty re.body. I have tried so many things with no luck. Am I missing something? Code snippet.
I would appreciate a point in the right direction
Thanks In Advance
PH.
service.ts
export interface Products{
_id: string,
name: string
}
#Injectable({
providedIn: 'root'
})
export class SearchService {
constructor(private http:HttpClient) { }
searchProducts(query:string){
console.log("Does it get my searchProducts");
return this.http.post<{payload: Array<Products>}>(productsUrl, {payload: query}, {
headers: new HttpHeaders({'Content-Type': 'application.json'})
}).pipe(
map(data => data.payload)
);
}
}
header.ts
sendData(event:any){
//console.log(event.target.value);
let query:string = event.target.value;
//Will match if query is nothing or only spaces
let matchSpaces:any=query.match(/\s*/);
console.log("What about match");
if(matchSpaces[0] === query){
console.log("What about query");
//.products=[];
console.log("what is in collection", this.products);
this.hasQuery = false;
return;
}
console.log("about to call service")
this.searchService.searchProducts(query.trim()).subscribe((results) =>{
console.log("does it get pass subscribe")
// this.products = results;
this.hasQuery = true;
console.log(results);
})
}
route file getProducts.js
var express = require('express');
const cors = require('cors');
var bodyParser = require('body-parser')
const Products = require('../../../liveSearch');
const { query } = require('express');
var router = express.Router();
const app = express();
router.get('/', function(req, res){
res.send('GET route on api here.');
});
/*router.post('/getproducts', function(req,res){
res.send("Trying to post")
});*/
/*app.use(cors());
var corsOptions = {
origin: 'http://localhost:4200',
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}*/
router.post('/getProducts', async(req, res) =>{
let payload=req.body;
//let payload= req.body.payload;
let search = await Products.find({name: {$regex: new RegExp('^'+payload+'.*',
'i')}}).exec();
//Limit search to 10
search = search.slice(0, 10);
console.log("Payload", payload)
//.log("Inside search",search);
res.status(201).json(payload) //added to see why I couldn't get
response
// res.send({payload:search});
})
server.js
const express = require('express');
const cors = require('cors');
const router = express.Router();
var bodyParser = require('body-parser');
const Products = require('./liveSearch');
const getProducts = require('.../../controllers/api/getProducts/getProducts')
//const products = require('.../../routes/products.js')
const mongoose = require('mongoose');
//mongoose.Promise = Promise;
mongoose.connect('mongodb://localhost/productLiveSearch', {useNewUrlParser:
true, useUnifiedTopology: true, });
const db = mongoose.connection;
db.on('error', error => console.log(error));
db.once('open', () =>{ console.log('Connected to Mongoose')});
const app = express();
app.use(function(req,res,next){
res.header('Access-Control-Allow-Origin', '*');
res.header('content-type','application/json');
res.header('Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization');
res.header('Access-Control-Allow-Methods','POST, GET, DELETE, PUT, OPTIONS');
res.header('Allow', 'GET, POST, OPTIONS, PUT, DELETE');
next();
});
app.use(cors());
var corsOptions = {
origin: 'http://localhost:4200',
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}
app.use(express.json());
app.use(express.urlencoded({extended:true}));
// app.use(express.json({ limit: "1000mb" }));
// app.use(express.urlencoded({ limit: "1000mb", extended: true }));
app.use('/', getProducts);
app.use('/getProducts', getProducts);
app.get('/', function(req, res){
res.send('hello world');
});
app.listen(process.env.Port|| 3000, () => {
console.log("Server has started on Port 3000");
});

How to resolve 502 Mysql query error on Netlify (Express server)

I have a React app + Express server deployed on netlify here. I have a simple api endpoint that queries my MySql DB on AWS.
When I make the api request I am given a "Failed to load resource: the server responded with a status of 502".
If I just return a simple
res.send("simple response")
then everything works fine and I get the response on the client. Could someone point me in the right direction on what I should be looking for?
I've tried to disable the skip_name_resolve parameter on my db to see if the hostname mattered, opening up access to all ports / ip's on the aws security group, look up common examples of express + mysql server implementations, lookup the netlify function docs, and using async await in the server.
// client.jsx
useEffect( () => {
fetch("/.netlify/functions/server/api/getSalesData")
.then(res => res.json())
.then(res => console.log(res));
// server.js
const express = require("express");
const bodyParser = require("body-parser");
const serverless = require('serverless-http');
const mysql = require("mysql");
const db = mysql.createConnection({ ... });
db.connect(function(err) {
if (err) throw err;
console.log('You are now connected...')
});
const app = express();
const router = express.Router();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
router.get("/api/getSalesData", (req, res) => {
// res.send({ express: "Hello from express" });
db.query("SELECT * FROM Sales LIMIT 5", (err, rows) => {
if (err) throw err;
res.send(rows);
});
});
app.use('/.netlify/functions/server', router);
module.exports = app;
module.exports.handler = serverless(app);

Stormpath wth Openshift has bad route

This setup is as follows:
Openshift gear with a nodejs component. npm install express body-parser express-stormpath --save. Server will run if you comment out the Stormpath calls/usage.
#!/bin/env node --harmony
// File: server.js
var fs = require('fs');
var express = require('express');
var bparser = require('body-parser');
var stormpath = require('express-stormpath');
var app = express();
// Log access URLs
app.use(function (req, res, next) {
console.log(req.url);
next();
});
// Default response
app.get('/', function(req, res){
res.send('<h2>Ghostfacers</h2>');
});
// Stormpath ApiKey,Secrct,etc set in environment
var baseFile = __dirname + '/index.html';
app.use(stormpath.init(app, {
web: {
spa: { enabled: true, view: baseFile }
}
}));
var port = process.env.OPENSHIFT_NODEJS_PORT;
var addr = process.env.OPENSHIFT_NODEJS_IP;
app.on('stormpath.ready',function() {
app.listen(port,addr, function() {
console.log('%s: Started %s:%d ...',
Date(Date.now() ),addr,port);
});
});
Errors in the nodejs log:
TypeError: Property 'route' of object function router(req, res, next) {
router.handle(req, res, next);
} is not a function at Function.proto.(anonymous function) [as get]...
...
lib/router/index.js:509:22
at addGetRoute ... lib/stormpath.js:137:14
After a good nights sleep and a cup of coffee I was able to get past this issue by using express version 4.x instead of version 3.x. I will submit a ticket to Stormpath to state this dependency.

Connecting to MongoDB using Express

I am having trouble understanding what needs to be done in order to connect to MongoDB so i can insert an Object into the database. I am new to using Express as well as MongoDB and don't have a full grasp on the both of them yet.
My app.js which was created using the standard Express setup is as follows.
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var ex_session = require('express-session');
var dateformat = require('dateformat');
var MongoClient = require('mongodb').MongoClient;
var ObjectID = require('mongodb').ObjectID;
var url = 'mongodb://localhost:27017/contacts'
var index = require('./routes/index');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
My index.js is as follows and what i would like to happen is when a post request is made from /mailer, a connection is made to the MongoDB in order to set up for an insert.
var express = require('express');
var router = express.Router();
var url = 'mongodb://localhost:27017/contacts';
var contacts;
/* GET home page. */
var start = function(req, res, next){
console.log("Starting!");
res.render('mailer',{});
}
router.get('/', start);
router.get('/mailer', start);
/* Post mailer Page insert into database*/
router.post('/mailer', function(req, res, next){
res.render('thanks');
console.log("Welcome to the Thank You Page");
MongoClient.connect(url, function(err, db){
if(err == NULL){
console.log("Connected to database");
// parse the body of the page and set up object to send to the
// database
}
});
});
router.get('/contact', function(req, res){
res.render('contact', {});
})
module.exports = router;
*for express ,
var mongo = require('mongodb');
var MongoClient = mongo.MongoClient;
MongoClient.connect('mongodb://'+DB_USERNAME+':'+DB_PASSWORD+'#'+DB_HOST+':'DB_PORT+'/'+DB_NAME,function(err, db){
if(err)
console.log(err);
else
{
console.log('Mongo Conn....');
}
});
//for local server for express
//in local server DBPASSWOAD and DBusername not required
MongoClient.connect('mongodb://'+DB_HOST+':'+DB_PORT+'/'+DB_NAME,function(err, db){
if(err)
console.log(err);
else
{
console.log('Mongo Conn....');
}
});
Your code is super mess,I can show your my configuration and u can refer to.
db.js
import mongoose from 'mongoose';
export default function connectDB() {
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/contacts');
mongoose.connection.once('open', function () {
console.log('mongodb connected.');
});
};
app.js
import connectDB from "db.js";
connectDB();
user.model.js
import mongoose from 'mongoose';
const schema = mongoose.Schema({
email: {type: String, required: true},
mobile: {type: String},
password: {type: String, required: true},
});
const User = mongoose.model('User', schema, 'user');
export default User;
then in your router file u can call User.find() or User.update or ...

Is there a way to include jade file directly in html file?

How can I combine a node.js website that its frontend is based on html with another node.js website that its frontend is based on jade template engine? I am using Express framework.
On the frontend there are four files: index.html, index2.html, chat1.html, chat2.html, which are located in the public folder. The blog website that I want to add to this website has only jade template engine, which are located in the views folder.
The index.html (which is in public folder) is the entry point to the home page of the website. When from index.html I refer to index3.jade, which is the Home page of the second app, i.e., blog jade app, Chrome browser states: "404 Not Found". However, I can go to the other two pages of the blog jade website, i.e., Add Post and Add Category. It is only the Home page of the blog jade app that is not being displayed.
So, I am not able to see only the Home page of the blog jade app, which starts at the root directory. Both the html app and the blog jade app start at the root directory. I was able to make the blog jade app to be displayed at the root directory, but then I could not see the html app, which also starts at the root directory.
Here is how I referred to each file from index.html front page:
`<li>gallery</li>`
`<li>chat</li>`
`<li>blog</li>`
Is there a way to have the home page of the blog jade app to be displayed at a directory other than the root directory?
Here is the related app.js code:
// Gallery HTML Code
var routes = require('./');
app.get('/public/index.html');
// Blog Code
var mongo = require('mongodb');
var db = require('monk')('localhost/nodeblog');
var routes = require('./');
var routes = require('./routes/index3');
var posts = require('./routes/posts');
var categories = require('./routes/categories');
var app = express();
app.locals.moment = require('moment');
app.locals.truncateText = function(text, length) {
var truncatedText = text.substring(0, length);
return truncatedText;
}
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// Express Session
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
// Express Validator
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.'),
root = namespace.shift(),
formParam = root;
while (namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param: formParam,
msg: msg,
value: value
};
}
}));
// Connect-Flash from Express-Messages
app.use(flash());
app.use(function(req, res, next) {
res.locals.messages = require('express-messages')(req, res);
next();
});
// Make our db accessible to our router
app.use(function(req, res, next) {
req.db = db;
next();
});
app.use('/index3', routes);
app.use('/posts', posts);
app.use('/categories', categories);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
Here is the related code from index3.js in the routes folder:
router.get('index3', function(req, res, next) {
var db = req.db;
var posts = db.get('posts');
posts.find({}, {}, function(err, posts) {
res.render('index3', { posts: posts });
});
});
module.exports = router;
Here is the related code from index.js in the routes folder:
router.get('/', function(req, res, next) {
res.render('public/index.html');
});
module.exports = router;