I'm on my localhost and when i start the server it shows nothing. When i go to localhost:8080/register it should show "asdasd" (as you can see in the code) but it doesnt work.
Can you guys help me out? Thank you very much!
const U2F = require("u2f");
const Express = require("express");
const BodyParser = require("body-parser");
const Cors = require("cors");
const HTTP = require("http");
const FS = require("fs");
const session = require("express-session");
const APP_ID = "http://localhost:8080/";
var app = Express();
app.use(session({ secret: "test", cookie: { secure: true, maxAge: 60000 }, saveUninitialized: true, resave: true }));
app.use(BodyParser.json());
app.use(BodyParser.urlencoded({ extended: true }));
app.use(Cors({ origin: [APP_ID], credentials: true }));
var user;
app.get("/", (request, response, next) => {
response.end("Hello Test");
});
app.get("/register", (request, response, next) => {
console.log("asdasd");
});
app.post("/register", (request, response, next) => {});
app.get("/login", (request, response, next) => { });
app.post("/login", (request, response, next) => { });
HTTP.createServer(function (request, response){
response.end();
}).listen(8080);
1) for a start your are logging "asdasd" to the console and not responding to the request made at the "/register" endpoint, just modify your code to the one below.
app.get("/register", (request, response, next) => {
response.end("asdasd");
});
2) you have not actually created a server for app , http.createserver is not tied to app
modify your code to the below
const server = HTTP.createServer(app);
server.listen(8080,()=>console.log("server is listening on port 8080")
Just pass app(returned by express) inside HTTP.createServer
HTTP.createServer(app).listen(8080);
Related
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.
On the client side, I have an application based on threejs an d javascript. I want to send data to the server written in express using fetch. Unfortunately, the server does not receive the data and the browser also gives an error:
Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource.
Application:
this.username = prompt("Username:");
const body = JSON.stringify({ username: this.username });
fetch("http://localhost:3000/addUser", { method: "POST", body })
.then((response) => response.json())
.then(
(data) => (
console.log(data), (this.aktualny_album_piosenki = data.files)
)
);
Server:
var express = require("express")
var app = express()
const PORT = 3000;
var path = require("path");
app.use(express.static('dist'));
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var cors = require('cors');
app.use(cors());
app.post("/addUser", function (req, res) {
console.log(req.body)
})
I might be wrong but maybe try... (very bottom of your main server file)
app.listen((PORT) => {
console.log(`app is listening on port ${PORT}`);
})
is required maybe? I have this chunk of code in every project of my own so maybe that could fix the server not recognizing the api request
express documentation on app listen
heres what I use typically... this is a boilerplate for every one of my projects
const express = require("express");
const app = express();
const connectDB = require("./config/db.js");
const router = express.Router();
const config = require("config");
// init middleware
const bodyParser = require('body-parser');
const cors = require("cors");
const mongoDB = require("./config/db.js");
const path = require("path");
const http = require("http");
const server = http.createServer(app);
const io = require('socket.io')(server, {
cors: {
origin: '*',
}
});
const xss = require('xss-clean');
const helmet = require("helmet");
const mongoSanitize = require('express-mongo-sanitize');
const rateLimit = require("express-rate-limit");
const PORT = process.env.PORT || 5000;
mongoDB();
app.options('*', cors());
app.use('*', cors());
app.use(cors());
const limitSize = (fn) => {
return (req, res, next) => {
if (req.path === '/upload/profile/pic/video') {
fn(req, res, next);
} else {
next();
}
}
}
const limiter = rateLimit({
max: 100,// max requests
windowMs: 60 * 60 * 1000 * 1000, // remove the last 1000 for production
message: 'Too many requests' // message to send
});
app.use(xss());
app.use(helmet());
app.use(mongoSanitize());
app.use(limiter);
// app.use routes go here... e.g. app.use("/login", require("./routes/file.js");
app.get('*', function(req, res) {
res.sendFile(__dirname, './client/public/index.html')
})
app.get('*', cors(), function(_, res) {
res.sendFile(__dirname, './client/build/index.html'), function(err) {
if (err) {
res.status(500).send(err)
};
};
});
app.get('/*', cors(), function(_, res) {
res.sendFile(__dirname, './client/build/index.html'), function(err) {
if (err) {
res.status(500).send(err)
};
};
});
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", '*');
res.header("Access-Control-Allow-Credentials", true);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header("Access-Control-Allow-Headers", 'Origin,X-Requested-With,Content-Type,Accept,content-type,application/json');
next();
});
if (process.env.NODE_ENV === "production") {
// Express will serve up production files
app.use(express.static("client/build"));
// serve up index.html file if it doenst recognize the route
app.get('*', cors(), function(_, res) {
res.sendFile(__dirname, './client/build/index.html'), function(err) {
if (err) {
res.status(500).send(err)
}
}
})
app.get('/*', cors(), function(_, res) {
res.sendFile(path.join(__dirname, './client/build/index.html'), function(err) {
if (err) {
res.status(500).send(err)
}
})
})
};
io.on("connection", socket => {
console.log("New client connected");
socket.on("disconnect", () => console.log("Client disconnected"));
});
server.listen(PORT, () => {
console.log(`Server listening on port ${PORT}!`);
});
client-side fetch request looks good to me its prob a server/express.JS thing but like i said i may be wrong but worth trying
My project is bundled on webpack. I've a form which post data to other local server, where saving in txt file. All is okay, data saves correctly, but after a few minutes, on client returns alert "net::ERR_EMPTY_RESPONSE" and then the same form values save to file second time. Why is it saves twice? How to fix this problem.
My fetch post request:
fetch("http://localhost:4000/post", {
method: "POST",
headers: {
"Content-Type": "application/json;charset=utf-8"
},
body: JSON.stringify(fragment),
if(err) {
throw err;
}
})
.then(console.log(fragment))
.catch(alert);
My server:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const fs = require('fs');
const cors = require('cors');
app.get('/', (req, res) => {
res.send('hello')
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors({
allowedOrigins: [
'http://localhost:9000'
]
}));
app.get('/post', (req, res) => {
console.log(req.body)
res.send('post')
})
app.post('/post', (req, res) => {
res = 0;
if (req.body.film.includes('день: Понеділок')) {
fs.appendFile('booking.monday.txt',
`${req.body.name},${req.body.number},${req.body.film}\n`,
function (err) {
if (err) throw err;
console.log('Saved!');
});
}
})
I've recently started looking at U2F in Node.js and Javascript.
I get the error: TypeError: Cannot read property 'registerResponse' of undefined
Before receiving the error on the server i get the following returned:
{errorCode: 5, errorMessage: "NotAllowedError: The operation either timed out or…://w3c.github.io/webauthn/#sec-assertion-privacy."}
The server is using HTTPS and a self signed cert on localhost in Mac os
What could be the issue? The response seems to be empty; and i dont get asked to insert the usb in the browser.
app.js:
const U2F = require("u2f");
const Cors = require("cors");
const session = require("express-session");
const HTTPS = require("https");
const FS = require("fs");
const BodyParser = require("body-parser");
const express = require("express");
var app = express();
var routes = require("./routes")(app);
const APP_ID = "https://localhost:3000";
app.use(BodyParser.json());
app.use(BodyParser.urlencoded({ extended: true }));
app.use(session({ secret: "thepolyglotdeveloper", cookie: { secure: true, maxAge: 60000 }, saveUninitialized: true, resave: true }));
app.use(Cors({ origin: [APP_ID], credentials: true }));
HTTPS.createServer({
key: FS.readFileSync("server.key"),
cert: FS.readFileSync("server.crt")
}, app).listen(3000, () => {
console.log("Listening at :443...");
});
routes.js
const U2F = require("u2f");
const session = require("express-session");
const APP_ID = "https://localhost:3000";
var appRouter = function(app) {
var user;
app.get("/", function(req, res, next) {
res.sendFile(__dirname + '/index.html');
});
app.get("/register", function(req, res, next) {
var session = U2F.request(APP_ID);
app.set("session", JSON.stringify(session));
console.log("session: " + JSON.stringify(session));
res.send(session);
});
app.post("/register", function (req, res, next) {
console.log("res2: " + req.body);
var registration = U2F.checkRegistration(JSON.parse(app.get("session")), req.body.registerResponse);
if(!registration.successful) {
return res.status(500).send({ message: "error" });
} else {
console.log("error");
}
user = registration;
res.send(registration);
});
}
module.exports = appRouter;
index.html
$("#register").click(() => {
if(window.u2f && window.u2f.register) {
$.get("/register", result => {
console.log(result);
window.u2f.register(result.appId, [result], [], response => {
console.log(response);
$.post("/register", { registerResponse: response }, result => {
console.log(result);
});
console.log(response);
});
});
} else {
document.write("<p>U2F is not supported</p>");
}
});
It seems like the request is timing out, or is not allowed. I've tried looking for the solution and so on; but there is little to no information regarding this issue.
Any help is much appreciated!
You are using var routes = require("./routes")(app); before BodyParser. Middlewares work in the order they are initialised. So, In your case body-parser in not even used in the routes.
Put the routes after bodyParser and cors:
var app = express();
const APP_ID = "https://localhost:3000";
app.use(BodyParser.json());
app.use(BodyParser.urlencoded({ extended: true }));
app.use(session({ secret: "thepolyglotdeveloper", cookie: { secure: true, maxAge: 60000 }, saveUninitialized: true, resave: true }));
app.use(Cors({ origin: [APP_ID], credentials: true }))
var routes = require("./routes")(app);
I'm trying to request the json file from stackexchange api and when the server loads save it on the client side so I can manipulate/change it locally.
I tried using this code but page just keep loading and nothing happens.
const express = require('express');
const bodyParser = require('body-parser');
const request = require('request');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json)
const surl = 'https://api.stackexchange.com/2.2/users/11097431?order=desc&sort=reputation&site=stackoverflow';
app.use('/', (req, res, next) => {
request(surl, (error, response, body) => {
// res.setHeader("Content-Type", "application/json; charset=utf-8");
res.json(body)
console.log('body:', body);
console.log('body:', req.body);
});
});
app.listen(3000, () => { console.log('On port 3000...') });
And if I comment out these two lines in my code below
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json)
It gives this kind of output.
"\u001f�\b��\u0000��8z00\u0000^{4���=�c��\u0000��#c�\u0002\u0000\u0000"
If anyone could give me a start that would be great! Thanks.
The output is gibberish because body is gzip compressed. It's not JSON, not even text:
To return it to browser, the easiest way is using pipe:
const request = require('request');
const surl = 'https://api.stackexchange.com/2.2/users/11097431?order=desc&sort=reputation&site=stackoverflow';
app.use('/', (req, res) => {
request(surl).pipe(res);
});
Or, if you want to manipulate/change the body, gzip: true option can be used:
const request = require('request');
const surl = 'https://api.stackexchange.com/2.2/users/11097431?order=desc&sort=reputation&site=stackoverflow';
app.use('/', (req, res) => {
request({
url: surl,
gzip: true
}, function(error, response, body) {
let bodyObj = JSON.parse(body);
// change bodyObj...
res.json(bodyObj);
});
});