I'm new with express/nodejs and all of this.
I try to include app.js
and myCustomCsrf.js
inside 'index.js' and is seems that is not working.
index.js
const app = require("./app.js");
const PORT = 5000
app.listen(PORT)
require("./myCustomCsrf.js")
app.get('/*', function(req, res) {
res.sendFile(path.join(__dirname, '/build/index.html'), function(err) {
if (err) {
res.status(500).send(err)
}
})
})
app.js
const express = require('express')
const path = require('path')
const mysql = require('mysql');
const crypto = require('crypto');
const cookieParser = require('cookie-parser')
const csrf = require('csurf')
const bodyParser = require('body-parser')
const cors = require('cors')
const session = require('express-session');
const { generateKey } = require('crypto');
// setup route middlewares
const csrfProtection = csrf({ cookie: true })
const parseForm = bodyParser.urlencoded({ extended: false })
// create express app
const app = express()
const corsOptions = {
origin: "http://localhost:3000",
credentials: true,
}
app.use(cors(corsOptions));
// setup session
app.use(session(
{
key: "guestSession",
secret: "yourSecretHere",
resave: false,
saveUninitialized: false,
cookie: {
maxAge: 1000 * 60 * 60 * 24
}
}
))
// parse cookies
// we need this because "cookie" is true in csrfProtection
app.use(cookieParser())
app.use(express.static(path.join(__dirname "/public")))
app.use(express.json())
module.exports = app
and this is myCustomCsrf.js
const app = require("../app");
// set his csrf value in useState in frontend (react)
app.get("/api/checkguest", csrfProtection, (req, res) => {
res.send({value: req.csrfToken() })
});
I know that I did not "include" the myCustomCsrf.js right. How can I do that?
Error:
ReferenceError: csrfProtection is not defined
I've tried many things, I really don't know what should I try again..
EDIT: I've solved this by using router https://stackoverflow.com/a/32284319/16661760
CodePudding user response:
Export csrfProtection
From app.js and use it in myCustomCsrf.js
in app.js:
module.exports = {app, csrfProtection}
in myCustomCsrf.js:
const {app, csrfProtection} = require("../app");
// set his csrf value in useState in frontend (react)
app.get("/api/checkguest", csrfProtection, (req, res) => {
res.send({value: req.csrfToken() })
});
also make changes in index.js file while importing app
in index.js:
const {app} = require("../app");
const PORT = 5000
app.listen(PORT)
require("./myCustomCsrf.js")
app.get('/*', function(req, res) {
res.sendFile(path.join(__dirname, '/build/index.html'), function(err) {
if (err) {
res.status(500).send(err)
}
})
})