Node js express js proxy - javascript

Here is an image of the error. I developed an application on AngularJS, and when I run node server by using public wifi my application is running fine. However, when I run it on org network/company wifi my application doesn't work. Any help?
server.js code
var express = require("express");
var open = require("open");
var bodyParser = require("body-parser");
var cookieParser = require("cookie-parser");
var fs = require("fs");
var path = require("path");
var auth = require("./api/auth");
//var users = require("./api/users");
var transactions = require("./api/transactions");
//var serviceTypes = require("./api/serviceTypes");
var app = express();
app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.json());
app.use(cookieParser());
app.use(express.static("boilerplate"));
app.use(express.static("./"));
app.listen(3000, function () {
console.log("server is running on port:3000");
open("http://localhost:3000/");
});
app.get("/", function (req, res) {
res.sendFile(path.join(__dirname, "boilerplate/index.html"));
});
app.use("/auth", auth);
//app.use("/users", users);
app.use("/transactions", transactions);
//app.use("/servicetypes", serviceTypes);

Related

ExpressJS: Misconfigured CSRF

I'm newbie in Node.js and Express and I'm trying to generate a security token using CSURF module. First, I have made a test using the documentation of the module and with only one file, for example, index.js works fine, but then, I have to try to separate the code in two files index.js and routes-api.js and it doesn't work and I don't know why.
index.js
This file requires "routes-api.js"
//Creación de un servidor con express
const express = require("express");
const app = express(); //Inicializamos express
//Accedemos a otros módulos
const morgan = require("morgan");
const bodyParser = require("body-parser");
const jwt = require("jsonwebtoken");
//Accedemos a propiedades de configuración
const config = require("./config");
//Rutas
const routes = require("./routes");
const routesAPI = require("./routes-api");
//Settings
app.set("app-name", config.server);
app.set("port", config.port);
app.set("super-secret", config.secret);
//Middlewares
// use body parser so we can get info from POST and/or URL parameters
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use(morgan("dev")); //Log request to the console
app.use((req, res, next) => {
console.log("Pasamos por la segunda función!!!");
next();
});
//Routing
app.use("/api", routesAPI);
app.use(routes);
//Server
app.listen(app.get("port"), () => {
console.log("Servidor " + app.get("app-name") + " escuchando!!!");
});
routes-api.js
var cookieParser = require('cookie-parser');
var csrf = require('csurf');
var bodyParser = require('body-parser');
var express = require('express');
const path = require("path");
const app = express();
const router = express.Router();
// setup route middlewares
var csrfProtection = csrf({ cookie: true });
var parseForm = bodyParser.urlencoded({ extended: false });
// parse cookies
// we need this because "cookie" is true in csrfProtection
app.use(cookieParser());
router.get("/", csrfProtection, (req, res) => {
console.log("crsf: " + req.csrfToken());
res.sendFile(path.join(__dirname + '/send.html'), { csrfToken: req.csrfToken() });
});
module.exports = router;
So, what am I doing wrong in routes-api.js file to get a misconfigured csrf error?
It looks like there's a new app in routes-api.js that's different than the existing app in index.js?
Maybe the routesAPI module should export a function that adds a router to an app.

issue with angular 4 and nodejs , serve index.html based on URL like /admin and /

Hi i have setup three project api(nodejs) , admin(angular 4) and website(angular 4) , after build i got two UI folder admin-dist and web-dist , I want to access these app based on URL '/admin' will access admin-dist and '/' will access web-dist , I have placed these two folder on of api folder
For accessing these app i have written node code like this ,But i am not able to access ,
Please help me, Thanks in advance ..
app.js
var express = require('express');
router = express.Router();
var port = process.env.PORT || 3000;
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var cookieParser = require('cookie-parser');
var fs = require('fs')
var morgan = require('morgan')
var path = require('path')
var cors = require('cors');
var User = require('./models/user.model');
var dbConfig = require('./config/db');
var app = express();
app.use(cors());
app.use(cookieParser());
// create a write stream (in append mode)
var accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), {flags: 'a'});
// setup the logger
app.use(morgan('combined', {stream: accessLogStream}));
mongoose.Promise = global.Promise;
mongoose.connect(dbConfig.db, function (err) {
if (err) {
console.log('faild to connect with mongo DB', err);
}
else {
console.log('Connection open with mongo db');
}
})
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use('/api', router);
var userRoute = require('./routes/user.route')(router);
// var profileRoute = require('./routes/profile.route')(app);
// var productRoute=require('./routes/products.route')(app);
app.use(express.static(__dirname + '/admin-dist'));
app.get('/admin', function (req, res) {
console.log('admin route');
return res.sendFile(path.resolve('./admin-dist/index.html'));
});
app.get('/admin/*', function (req, res) {
res.sendFile(path.resolve('./admin-dist/index.html'));
});
app.use(express.static(__dirname + '/front-dist'));
app.get('/', function (req, res) {
console.log('web route');
return res.sendFile(path.resolve('./front-dist/index.html'));
});
app.use('/*',function(req, res) {
return res.sendFile(path.resolve('./front-dist/index.html'));
});
app.listen(port, function (err) {
if (err) {
console.log(err);
}
else {
console.log('Server api runing on port ', port);
}
})

Node Express: Requests are taking Top-level domain as the subdomain ??

I am working on a express project where subdomains are used.
Now the problem i am facing is that my domain name is ("companyName.co.in") and my node JS code is considering companyName as the subdomain.
Here is my code:
server.js
var express = require('express');
var app = express();
var subdomain = require('express-subdomain');
var bodyParser = require('body-parser');
var path = require('path');
var expressValidator = require('express-validator');
var expressJwt = require('express-jwt');
var jwt = require('jsonwebtoken');
var cors = require('cors');
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
app.use(cors());
//app.use(cookieParser());
app.use(express.static('../app'));
app.use(express.static('static/'));
app.use('/api/user',require('./controllers/user.controller'));
var server = app.listen(3000,function(){
console.log('Server listening at 3000');
});
user.controller.js
var express = require('express');
var router = express.Router();
router.get("/details", getUserDetails);
function getUserDetails(req, res) {
var subdomain = (req.subdomains.length > 0) ? req.subdomains[0] : '';
console.log(subdomain)
}
module.exports = router;
So when i call the api/user/details i find that it gives the companyName as the subdomain.
like: requesting from "companyName.co.in"
subdomain should be null but it gives me subdomain as companyName.
Can you please help how can i let the node server know that "companyName.co.in" this is the host and also allow "*.companyName.co.in" where the subdomain can be anything.
You can solve this in your case by setting the 'subdomain offset' express app setting to 3.
http://expressjs.com/en/4x/api.html#app.settings.table
var express = require('express');
var app = express();
app.set('subdomain offset', 3);

node js post request.body undefined

server.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var session = require('express-session');
var fs = require('fs');
var router = require('./router/main')(app, fs);
var server = app.listen(3000, function(){
console.log('Express server has started on port 3000');
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
router/main.js
module.exports = function(app, fs)
{
app.post('/addUser/', function(req, res){
console.log(req.body);
});
}
I use postman tool!! requets param {"password" : "pass","name" : "dltlsdn"}
but... req.body is undefind.... why..??
Reorder the app.use statement. Earlier you were processing the request before passing through the body-parser.
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var session = require('express-session');
var fs = require('fs');
//body parser before routes
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
var router = require('./router/main')(app, fs);
var server = app.listen(3000, function(){
console.log('Express server has started on port 3000');
});
Hope it helped you.

How to access header information on node js?

How can i read cookie on node js ??
var socket = require( 'socket.io' );
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = socket.listen( server );
var port = process.env.PORT || 8000;
var mysql = require('mysql');
function parseCookies (request) {
var list = {},
rc = request.headers.cookie;
rc && rc.split(';').forEach(function( cookie ) {
var parts = cookie.split('=');
list[parts.shift().trim()] = decodeURI(parts.join('='));
});
return list;
}
http.createServer(function (request, response) {
// To Read a Cookie
var user_id= cookies.realtimeid;
console.log(user_id);
});
server.listen(port, function () {
console.log('Server listening at port %d', port);
var cookies = parseCookies();
console.log(cookies);
});
I am new on node and socket. I have to read cookie value that is set by codeignter.
How can i send header request on parseCookies from server.listen.
I see you are using express, so I suggest you to use the very well known module for it. cookie-parser https://www.npmjs.com/package/cookie-parser
Installation
npm install cookie-parser
HOW TO USE IT
var express = require('express')
var cookieParser = require('cookie-parser')
var app = express()
app.use(cookieParser())
So basically after your mysql require you can do app.use(cookieParser())
And then in every request you do in the req variable you will find the cookies with req.cookies
Example
var express = require('express')
var cookieParser = require('cookie-parser')
var app = express()
app.use(cookieParser())
app.get('/', function(req, res) {
console.log("Cookies: ", req.cookies)
})
app.listen(8080)

Categories

Resources