Can't access cookie on http in Heroku only https - javascript

I am having a strange issue with cookies in my node app. It is hosted on Heroku and I use JSON Web Tokens stored in a cookie that is authenticated by my express middleware. When I login on my Macbook pro, the cookie is successfully stored. However, when I use Linux Mint desktop, or an Android tablet, the site logs in but then redirects on protected routes and the cookie is never set.
This is where the cookie is set on login:
let token = jwt.sign({
username: user.username,
email: user.email
}, config.privateKey, {
expiresIn: '7d'
});
let userResponse = {
success: true,
message: 'Successfully logged in!',
id: user._id,
email: user.email,
username: user.username
}
// set cookie for 7 days
res.cookie('auth_token',
token,
{maxAge: 604800000, path: "/"}).json(userResponse);
Here is my server.js file:
'use strict';
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const env = process.env.NODE_ENV || "development";
const mongoose = require('mongoose');
const cookieParser = require('cookie-parser');
const config = require('./app/config/config.js');
process.env.PWD = process.cwd();
// Establish connection with MongoDB
mongoose.connect(config.db.connectString);
app.use(cookieParser());
// Allowing X-domain request
var allowCrossDomain = function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Cache-Control");
// intercept OPTIONS method
if ('OPTIONS' == req.method) {
res.send(200);
}
else {
next();
}
};
app.use(allowCrossDomain);
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static('public'));
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error: '));
db.once('open', () => {
console.log('Connected to sondage database');
});
// ===== Import Routers ======
const userRouter = require('./app/routes/user.routes')(express, app);
const pollRouter = require('./app/routes/poll.routes')(express, app);
const authRouter = require('./app/routes/auth.routes')(express, app);
app.use('/api/users', userRouter);
app.use('/api/polls', pollRouter);
app.use('/api/', authRouter);
// For all other requests, use React Router
app.get('*', function (request, response){
response.sendFile(process.env.PWD + '/public/index.html');
});
app.listen(process.env.PORT || 3000, () => {
console.log('Server running');
});
EDIT I have traced this down to a http vs https issue. If I use https in the request, the cookies work. Otherwise cookies aren't set. So I need a way to force the user to do HTTPS.

I was able to fix this using the heroku-ssl-redirect node package. This takes requests and forces the browser to use https for each request.

Related

Every API request makes 2 new Express Sessions, only keeping the second one for passing to the router once (MongoDB, Express Sessions, Node,Javascript

Im trying to initialize an express session to a Mongo store in my MERN application for passing a user's ID to my passport authentication flow, however it acts unaccordingly to how it should by my understanding.
For each request i make to my auth.routes.cjs, the app makes a completely new session disregarding the currently already initialized one, then makes ANOTHER one, and only the last one gets passed to the router/controller.
I've currently attached a console.log(req.session) to both my index.cjs and auth.routes.cjs for every function called, to get an overview of how and which data is being created and passed between the components.
Index.cjs passes a value of req.session.test='test', then logs session id and session
auth.routes.cjs changes req.session.test to 'test2', then logs session, but only for the second initialization, making it useless
this is what my terminal logs after a request
index.cjs
var FfmpegCommand = require('fluent-ffmpeg');
var command = new FfmpegCommand();
const rateLimit = require('express-rate-limit');
const fs = require('fs');
const passport = require('./middleware/passportInitialization.cjs');
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const morgan = require('morgan');
const fileUpload = require('express-fileupload');
const session = require('express-session');
const { v4: uuidv4 } = require('uuid');
const MongoDBStore = require('connect-mongodb-session')(session)
const store = new MongoDBStore({
uri: process.env.MONGODB_URI,
databaseName: 'test',
collection: 'sessions'
});
store.on('error', function (error) {
console.log(error);
});
const app = express()
const port = 4000;
const db = require("./models/index.cjs");
const Role = db.Role;
const uri = process.env.MONGODB_URI;
app.use(passport.initialize());
app.use(express.urlencoded({ extended: true }));
db.mongoose
.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
console.log("Successfully connect to MongoDB.");
initial();
})
.catch(err => {
console.error("Connection error", err);
process.exit();
});
app.use(session({
genid: () => {
return uuidv4() // use UUIDs for session IDs
},
secret: 'wdaoijiuwaheh23n4n23irfu9sujn398fhfmIUQHIG4bhyh9h',// TODO: change this to a random env string
store: store,
resave: false,
saveUninitialized: false,
cookie: {
secure: false,
maxAge: 1000 * 60 * 60 * 24,
sameSite: 'none'
}
}));
app.use(function (req, res, next) {
req.session.test = "test";
console.log('req.session', req.session.id);
console.log(req.session)
next();
});
var filter = require('content-filter');
app.use(filter());
app.use(fileUpload({
createParentPath: true
}));
const corsOptions ={
origin:'http://localhost:4001',
credentials:true, //access-control-allow-credentials:true
optionSuccessStatus:200
}
app.use(cors(corsOptions));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(morgan('dev'));
app.use(express.json());
app.use('/uploads', express.static('uploads'));
require('./routes/auth.routes.cjs')(app)
require('./routes/user.routes.cjs')(app)
require('./routes/upload.routes.cjs')(app)
app.use(function (req, res, next) {
req.session.test = "test";
next();
});
auth.routes.cjs
const verifySignUp = require("../middleware/verifySignUp.cjs");
const controller = require("../controllers/auth.controller.cjs")
const passport = require('../middleware/passportInitialization.cjs');
const authJwt = require("../middleware/authJwt.cjs");
module.exports = function(app) {
app.use(function(req, res, next) {
req.session.test = "test2";
console.log(req.session.id)
console.log (req.session)
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4001');
//res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
//res.setHeader('Access-Control-Allow-Credentials', true);
res.setHeader(
"Access-Control-Allow-Headers",
"x-access-token, Content-Type, Accept"
);
next();
});
app.post("/api/auth/refreshtoken", controller.refreshToken);
app.post(
"/api/auth/signup",
[
verifySignUp.checkDuplicateUsernameOrEmail,
verifySignUp.checkRolesExisted
],
controller.signup
);
//endpoint named /api/auth/signin calls the controller.signin function and then saves the user id to the session
app.post("/api/auth/signin", controller.signin);
app.get("/api/auth/google",[authJwt.verifyIfUserIsLoggedIn], passport.authenticate('youtube', {display: 'popup', failureMessage: true, failureRedirect: '/login'}
));
//endpoint with access-control-allow-origin: *
app.get("/api/auth/google/callback", passport.authenticate('youtube', {failureMessage: true, failureRedirect: '/login'}), function(req, res) {
// Successful authentication, redirect home.
const userYoutubeData = req.userYoutubeData;
console.log('userYoutubeData', userYoutubeData);
console.log('shall be linked to user id ' + req.session);
res.header(
"Access-Control-Allow-Origin", "*"
);
res.redirect('http://localhost:4001/upload');
//res.json({message:"Success", username: req.user.username});
});
}
I've been stuck on this for the past two weeks with no luck whatsoever. Hoping that someone could give me insight on my possibly misinterpreted logic behind this flow.

Localhost accessed req.session.userid but virtual host can't be reached

here is some problem that i have... i have been tried days to figure it out but nothing make it working.
i have Node.js Express session on backend and there are users, when i make login i set req.session.userId = "userid" and i have middleware that check if req.session.userId exist and then next() so on Localhost everything worked fine but when i hosted my website i can’t access the req.session.userId it's mean the Middleware don’t next()
Frondend hosted: Netlify
Backend hosted: Nodechef
Mysql hosted: Nodechef
i don’t know, maybe i missed something or that i have to made some
changes when hosting...
i hope you guys have solution for me 🙌🏻
index.js
const express = require('express');
const cookieParser = require("cookie-parser");
const session = require('express-session');
const cors = require('cors');
const app = express();
app.use(express.json());
app.use(cookieParser());
app.use(cors({
origin: '***********',
credentials: true
}));
app.all('/', function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Credentials", true);
next();
});
app.use(session({
secret: "******",
name: "*****",
saveUninitialized: true,
resave: true,
cookie: {
domain: '*******',
secure: true,
maxAge: 1000 * 60 * 60 * 24 * 365,
}
}))
app.get('/', (req, res) => {
res.send({ msg: "seccess" })
})
app.use('/users', require('./routes/users'))
const PORT = 3000
app.listen(process.env.PORT || PORT, () => {
console.log(`Express server listening on port ${PORT} `);
});
users/login
const router = require('express').Router()
router.post('/login', (req, res) => {
const { userEmail, userPassword } = req.body
db.query(`SELECT * FROM users WHERE userEmail = ?`, userEmail,
(err, result) => {
if (err) {
return res.send({ err: err })
} else {
if (!userEmail || !userPassword)
req.session.userId = user.id
res.send({ msg: "Login Succes", req: req.session, user: user.id })
}
})
});
Middleware
module.exports.onlyLoggedUsers = (req, res, next) => {
if (req.session.userId) {
next()
} else {
res.status(200).send({err:"sensetive content for logged users only, plesae log in"})
}
}
I just added app.enable('trust proxy')
and it is work temporarily, in safari this not work and also on smartphone, if I got to setting in safari and turn of Prevent Cross-Site Tracking it is working so my question is how I can run the application without turn of Prevent Cross-Site Tracking.

Heroku Error: ENOENT: no such file or directory, open '.env'

I'm trying to push my application to Heroku, but I'm running into some issues:
Error: ENOENT: no such file or directory, open '.env'
2019-04-10T01:38:23.050188+00:00 app[web.1]: 1 at
Object.openSync (fs.js:438:3) 2019-04-10T01:38:23.050190+00:00
app[web.1]: 1 at Object.readFileSync (fs.js:343:35)
2019-04-10T01:38:23.050192+00:00 app[web.1]: 1 at
Object. (/app/config/database.js:4:39)
It seems that the error is the variable envConfig, but i need it for database to work.
As of now, I'm getting
Here is my config/database.js:
if (!process.env.PG_DB) {
const fs = require('fs')
const dotenv = require('dotenv')
// dotenv, but i need this make the database work
const envConfig = dotenv.parse(fs.readFileSync('.env'))
for (var k in envConfig) {
process.env[k] = envConfig[k]
}
console.log('[api][sequelize] Loaded database ENV vars from .env file')
}
module.exports = {
development: {
username: process.env.POSTGRES_USER,
password: process.env.POSTGRES_PASSWORD,
database: process.env.POSTGRES_DB,
host: process.env.POSTGRES_HOST,
dialect: 'postgres',
migrationStorageTableName: 'sequelize_meta'
},
production: {
username: "root",
password: null,
database: "*********some postgress url",
host: "127.0.0.1",
dialect: "postgres"
}
And my app.js:
var express = require('express');
var app = express();
var userRoute = require('./routes/users');
var postRoute = require('./routes/posts');
var bodyParser = require('body-parser');
var logger = require('morgan');
var session = require('express-session');
var cookieParser = require('cookie-parser') ;
var dotenv = require('dotenv');
var env = dotenv.config();
var cors = require('cors');
var models = require('./models/');
const port = process.env.PORT || 8000;
const passport = require('passport');
const path = require('path');
// const allowOrigin = process.env.ALLOW_ORIGIN || '*'
// CORS Middleware
if (!process.env.PORT) {
require('dotenv').config()
}
if (!process.env.PORT) {
console.log('[api][port] 8000 set as default')
console.log('[api][header] Access-Control-Allow-Origin: * set as default')
} else {
console.log('[api][node] Loaded ENV vars from .env file')
console.log(`[api][port] ${process.env.PORT}`)
console.log(`[api][header] Access-Control-Allow-Origin: ${process.env.ALLOW_ORIGIN}`)
}
require('./config/passport-github');
require('./config/passport');
app.use(logger('dev'));
app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser());
app.use(session({
secret : process.env.JWT_SECRET,
saveUninitialized: false,
maxAge: 1000 * 60 * 60 * 84,
resave: false
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended:false}));
const isAuthenticated = function(req, res, next){
if(req.isAuthenticated()){
next();
console.log('this works');
}else{
res.redirect('http://127.0.0.1:8001/signIn');
}
}
// app.use(function(req, res, next) {
// res.header('Access-Control-Allow-Origin', '*');
// // res.header('Access-Control-Allow-Credentials', true);
// res.header("preflightContinue", false)
// // res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
// res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
// next();
// });
app.use(cors({
'allowedHeaders': ['Content-Type'], // headers that React is sending to the API
'exposedHeaders': ['Content-Type'], // headers that you are sending back to React
'origin': '*',
'methods': 'GET,HEAD,PUT,PATCH,POST,DELETE',
'preflightContinue': false
}));
app.use('/api/users', userRoute );
app.use('/api/posts', isAuthenticated, postRoute );
app.use(function(req, res, next) {
res.locals.user = req.user; // This is the important line
// req.session.user = user
console.log(res.locals.user);
next();
});
models.sequelize.sync().then(() => {
const server = app.listen(port, () => {
console.log(`Server is up and running on port ${port}`);
});
});
Before you do anything else, if those are your real credentials you should invalidate them immediately. They are forever
compromised, and you need to generate new ones. Editing them out of your question is not enough.
You can change
const envConfig = dotenv.parse(fs.readFileSync('.env'))
to
const envConfig = dotenv.config({silent: true})
You don't need to manually read the file here, and skipping it lets you gracefully handle the case when it doesn't exist. There's also no need to manually set values in process.env:
for (var k in envConfig) {
process.env[k] = envConfig[k]
}
This can be entirely skipped. Dotenv takes care of this itself. Therefore, you don't need envConfig either, reducing all of that to just
dotenv.config({silent: true})
If .env exists, its contents will be added to what's already in process.env. In development, this gives you a convenient way to set your database connection information.
In production, .env shouldn't exist, and your database connection information definitely shouldn't be hard-coded. Instead, your database connection information should come from one or more Heroku config vars (these are environment variables that should already be available via process.env). Your database addon has probably already set the DATABASE_URL variable for you.
For things in your .env that you've set yourself, set a Heroku config var for its production value. You can do that through the Heroku web dashboard or via the Heroku CLI:
heroku config:set SOME_VARIABLE=foo

Cannot post data from React Js to Node js

I am beginner use React Js and Node Js, I get a problem, I cannot post my data from React Js to Node Js, I have been looking for the way but failed all, I don't know why.
This is my complete code.
This is my react file 'member.js', run on port 3000 (http://localhost:3000/member).
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
class Member extends Component {
constructor() {
super();
this.state = { player: {} };
}
handleSubmit(e) {
e.preventDefault();
fetch('http://localhost:4000/player', {
mode: 'no-cors',
method: 'post',
headers: {
"Content-Type": "text/plain"
},
body: JSON.stringify({
number: 123,
name: "John",
position: "Andrew"
})
}).then(function(response) {
console.log(response);
}).catch(function(error) {
console.log('Request failed', error)
});
}
render() {
return (
<div className="member-page">
<form>
<input type="submit" onClick={this.handleSubmit.bind(this)} />
</form>
</div>
)
}
}
export default Member;
and this is my node file 'player.js', run on port 4000 (http://localhost:4000/player).
var http = require('http');
var mysql = require('mysql');
var express = require('express');
var app = express();
var connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "react_1"
});
app.post('/player', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
var player = req.body;
var query = connection.query('INSERT INTO player VALUES ?', player, function(err, result) {
// Neat!
});
res.end('Success');
});
app.listen(4000, function() {
console.log('Example app listening on port 4000!');
});
I don't know where I do a mistake, please anyone correct my code either member.js or player.js.
Thank you very much for all the help.
I agree with #robertklep. I think problem is in var player = req.body;
Try:
Install body-parser npm package
npm i -S body-parser
Configure body-parser
var http = require('http');
var mysql = require('mysql');
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
//enable CORS
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
var connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "react_1"
});
app.post('/player', (req, res) => {
var player = req.body;
var query = connection.query('INSERT INTO player VALUES ?', player, (error, results, fields) => {
if (error) throw error;
// Neat!
});
res.send('Success');
});
app.listen(4000, function() {
console.log('Example app listening on port 4000!');
});
const express = require('express')
var bodyParser = require('body-parser')
const app = express()
var router = express.Router();
router.use( bodyParser.json() ); // to support JSON-encoded bodies
router.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(5000, () => {
console.log('Example app listening on port 5000!')
})
app.use('/', router);
Try to Configure your node server like this
First install body-parser using :
npm install body-parser
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
If you are passing string data then use
app.use(bodyParser.text());
Otherwise if you are passing data as Json then use
app.use(bodyParser.Json());
It should work in your case.

How to protect a http post from Angular 2 to Express Server

How do I protect a post call from a angular2 application to a Express server?
In my angular2 application I have a the following HTTP Post.
const headers = new Headers();
headers.append('Content-Type', 'application/json');
const data = {
email: this.form.value.email
};
this.http.post('http://localhost:8080/api/user/email', data, {
headers: headers
})
Now I want to make sure that only my angular 2 application can make the post call to the user api. I did some research about csrf in combination with Express and Angular 2. In my Angular 2 application I made the following implementation to the app.module.ts file.
import { HttpModule, XSRFStrategy, CookieXSRFStrategy } from '#angular/http';
providers: [ {
provide: XSRFStrategy,
useValue: new CookieXSRFStrategy('csrftoken', 'X-CSRFToken')
} ]
I think this is the right way to implement a XSRFStrategy to Angular 2?
For the implementation in Express I followed a few tutorials, but without any success. Most of the time I received:
ForbiddenError: invalid csrf token
How do I implement the CSRF part in my Express api. Here is my Express config:
// call the packages we need
var express = require('express'); // call express
var app = express(); // define our app using express
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var csrf = require('csurf');
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
var port = process.env.PORT || 8080; // set our port
// ROUTES FOR OUR API
// =============================================================================
var router = express.Router();
router.use(function (req, res, next) {
console.log('Something is happening.');
res.setHeader("Access-Control-Allow-Origin", "http://localhost:4200");
res.setHeader("Access-Control-Allow-Credentials", "true");
res.setHeader("Access-Control-Allow-Methods", "POST");
res.setHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
res.setHeader('Content-Type', 'application/json');
next();
});
app.use('/api', router);
router.post('/user/email', function (req, res) {
..... [how to make sure that this post can only be fired from my angular 2 application ]
}
Update #1
Did some more research and found the following in the Angular 2 docs:
//By default, Angular will look for a cookie called `'XSRF-TOKEN'`, and set
//* an HTTP request header called `'X-XSRF-TOKEN'` with the value of the cookie on each request,
So in my Express application I added the following parts:
const cookieOptions = {
key: 'XSRF-TOKEN',
secure: false,
httpOnly: false,
maxAge: 3600000
}
var csrfProtection = csrf({
cookie: cookieOptions
})
and in the post route I implemented the protection as follow:
router.post('/user/email', csrfProtection, function (req, res) {
console.log('post incomming');
}):
I got the following response headers back
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers
Access-Control-Allow-Methods:POST
Access-Control-Allow-Origin:http://localhost:4200
Connection:keep-alive
Content-Length:1167
Content-Type:text/html; charset=utf-8
Date:Mon, 21 Nov 2016 20:07:12 GMT
set-cookie:XSRF-TOKEN=O4JKkjAZRik2H7ml0DoxDc8s; Max-Age=3600000; Path=/
X-Content-Type-Options:nosniff
X-Powered-By:Express
And the request headers:
Accept:*/*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.8,nl;q=0.6
Connection:keep-alive
Content-Length:38
content-type:application/json
Host:localhost:8080
Origin:http://localhost:4200
Referer:http://localhost:4200/profile/users
How to implement CSRF protection with Angular2 and Express
By default, Angular will look for a cookie called 'XSRF-TOKEN', and set
an HTTP request header called 'X-XSRF-TOKEN' with the value of the cookie on each request.
To make sure that our backend can set a XSRF-TOKEN cookie, we have to proxy our calls to the api running on port 8080. We can do that with a proxy.config.json file.
{
"/api/*" : {
"target": "http://localhost:8080",
"secure": false,
"logLevel": "debug"
}
}
And in our package.json file we modify the scripts/start function to use our proxy.config.json file:
"scripts": {
"start": "ng serve --proxy-config proxy.config.json",
}
Now every time we run npm start our calls to /api are proxied to localhost:8080. Now we are ready to make a post call to our api server.
In our component we make a http post call and we set the headers to use content-type application/json.
ourfunction() {
const headers = new Headers();
headers.append('Content-Type', 'application/json');
data = { key:value }
this.http.post('/api/user/email', data, {
headers: headers
}).subscribe( (resp: any) => console.log('resp', resp));
}
That is everything we need to do at the Angular2 side. Now we are implement the Express side.
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var csrf = require('csurf');
var cors = require('cors')
We initialise our app and defining some middleware to use in our application.
const cookieOptions = {
key: 'XSRF-TOKEN',
secure: false,
httpOnly: false,
maxAge: 3600
}
const corsOptions = {
origin: 'http://localhost:4200',
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
};
Here we are setting the options to use for csrf and cors middleware.
const port = process.env.PORT || 8080; // set our port
const csrfProtection = csrf({ cookie: cookieOptions })
const router = express.Router();
Implementing the middelware. The order is very important to get the correct results.
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use('/api', router);
app.use(cors(corsOptions));
app.use(cookieParser());
app.use(csrfProtection);
router.use(function (req, res, next) {
res.setHeader('Content-Type', 'application/json');
next();
});
Thats all we need to do on the Express side. Now we can secure our post calls with a CSRF token.
Compleet express server file
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var csrf = require('csurf');
var cors = require('cors')
const cookieOptions = {
key: 'XSRF-TOKEN',
secure: false,
httpOnly: false,
maxAge: 3600
}
const corsOptions = {
origin: 'http://localhost:4200',
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
};
const port = process.env.PORT || 8080; // set our port
const csrfProtection = csrf({ cookie: cookieOptions })
const router = express.Router();
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use('/api', router);
app.use(cors(corsOptions));
app.use(cookieParser());
app.use(csrfProtection);
router.use(function (req, res, next) {
res.setHeader('Content-Type', 'application/json');
next();
});
router.post('/user/email', function (req, res) {
console.log('post incomming');
console.log('req', req.body);
res.send('testing..');
});
app.listen(port);
console.log('Magic happens on port ' + port);

Categories

Resources