NodeSSPI 2 Minute Timeout on Post - node.js

When I send a request to my server I have no problem, but when I POST I run into a server timeout. (2 minutes by default, but if I add server.setTimeout(15000) I get a 15 second delay.) Once the server times out the process completes as expected. Interestingly, if I add a console.log(res) before the res.finished || next() the delay goes away.
post.html:
<form action="http://localhost:3000" method="post">
<input type="text" name="user[name]">
<input type="text" name="user[email]">
<input type="submit" value="Submit">
</form>
test.js:
'use strict'
var express = require('express')
var app = express()
var server = require('http').createServer(app)
//server.setTimeout(15000);
const bodyParser = require("body-parser");
app.use(function (req, res, next) {
var nodeSSPI = require('node-sspi')
var nodeSSPIObj = new nodeSSPI({
retrieveGroups: true
})
nodeSSPIObj.authenticate(req, res, function(err){
//console.log(res);
res.finished || next()
})
})
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.post("/", function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write("<html>");
res.write("<body>");
res.write("<h1>My Header</h1>");
res.write("<p>My paragraph.</p>");
res.write("<p>Name = " + req.body.user.name + "</p>");
res.write("<p>Email = " + req.body.user.email + "</p>");
res.write("</body>");
res.write("</html>");
res.end();
console.log('End post');
});
// Start server
var port = process.env.PORT || 3000
server.listen(port, function () {
console.log('Express server listening on port %d in %s mode', port, app.get('env'))
})

It turns out the problem went away when I reordered the routing to put the bodyParser lines above the nodeSSPI check.
Specifically, I moved these lines:
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
Above:
app.use(function (req, res, next) {
var nodeSSPI = require('node-sspi');
var nodeSSPIObj = new nodeSSPI({
retrieveGroups: false
});
nodeSSPIObj.authenticate(req, res, function(err){
res.finished || next();
});
});

Related

How can I receive post data in a node js server with express?

I tried two middlewares but still getting this output in the terminal:
{}
my node js server code:
express = require('express');
bodyParser = require('body-parser');
const app = express();
//the middlewares i tried
app.use(express.urlencoded({extended: false}));
app.use(bodyParser());
app.get('/', (req, res) => {
res.sendFile(__dirname + '/client.html');
});
app.post('/test', (req, res) => {
res.send('this is a test path');
console.log(req.body);
});
app.listen(3000, () => {
console.log('server listening...');
});
my form (client.html file):
<form method="POST" action="/test">
<input type="text">
<input type="submit">
</form>
I also tried send the post data with postman. I know that the action in the html form is working because I can see the "this is a test path" output in the browser
try this
express = require('express');
bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/client.html');
});
app.post('/test', (req, res) => {
res.send('this is a test path');
console.log(req.body);
});
app.listen(3000, () => {
console.log('server listening...');
});
also in html form , add name property in input tag
<form method="POST" action="/test">
<input type="text" name="email">
<input type="submit">
</form>
in fact it works just like
app.use(express.urlencoded());
the wrong thing was the nameless input in the html form
you should write code like this
var app=express();
app.use(bodyparser.urlencoded({ extended: true }));
app.use(bodyparser.json());
app.post('/test', (req, res) => {
console.log(req.body.email);
res.send('this is a test path'+req.body.email);
});

node.js syntax error: SyntaxError: Unexpected end of input

I have an SyntaxError: Unexpected end of input. I'm new to Node. The error is on line 33 at }). I'm pretty sure it either has to do with the closing of a function but not quite sure.
var express = require('express');
var app = express();
var fs = require('fs');
var path = require('path');
app.use(express.static(path.join(__dirname, '/public')));
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json());
app.use('/', express.static(path.join(__dirname, 'public')));
app.get('/favorites', function(req, res){
var data = fs.readFileSync('./data.json');
res.setHeader('Content-Type', 'application/json');
res.send(data);
;
app.get('favorites', function(req, res){
if(!req.body.name || !req.body.oid){
res.send("Error");
return
var data = JSON.parse(fs.readFileSync('./data.json'));
data.push(req.body);
fs.writeFile('./data.json', JSON.stringify(data));
res.setHeader('Content-Type', 'application/json');
res.send(data);
};
app.list(3000, function(){
console.log("Listening on port 3000");
});
you forgot to close off the parenthesis for 2 get request
here:
app.get('/favorites', function(req, res){
var data = fs.readFileSync('./data.json');
res.setHeader('Content-Type', 'application/json');
res.send(data);
}); //here
and here:
app.get('favorites', function(req, res){
if(!req.body.name || !req.body.oid){
res.send("Error");
return
var data = JSON.parse(fs.readFileSync('./data.json'));
data.push(req.body);
fs.writeFile('./data.json', JSON.stringify(data));
res.setHeader('Content-Type', 'application/json');
res.send(data);
}); //here

Express router not working

I'm new to express and used yo-generator to create my project. The problem I'm facing is that routes with:
app.get('/something') are working fine, but
router.get('/something') are not working. I tried to research but could not solve the problem.
Here are my files:
app.js
var fs = require('fs');
var http = require('http');
var path = require('path');
var helmet = require('helmet');
var express = require('express');
var root = path.normalize(__dirname + '/');
var constant = require(root + '/app/util/constants.js');
var config = require(constant.APP_CONFIG_FILE);
var app = express();
app.use(helmet());
app.use(function(req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Headers", "DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type");
return next();
});
require('./config/express')(app, config);
http.createServer(app).listen(config.WEB_PORT, function() {
console.log('Server listening http on port ' + config.WEB_PORT);
});
module.exports = app;
Lines from express.js
var env = process.env.NODE_ENV || 'development';
app.locals.ENV = env;
app.locals.ENV_DEVELOPMENT = env == 'development';
app.set('views', config.ROOT + '/app/views');
app.set('view engine', 'ejs');
// app.use(favicon(config.root + '/public/img/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cookieParser());
app.use(compress());
app.use(express.static(config.ROOT + '/public'));
app.use(methodOverride());
var controllers = glob.sync(config.ROOT + '/app/controllers/*.js');
controllers.forEach(function(controller) {
require(controller)(app);
});
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
app/controllers/user-ctrl.js
var path = require('path');
var express = require('express');
var router = express.Router();
var root = path.normalize(__dirname + '/../..');
var constant = require(root + '/app/util/constants.js');
var service = require(constant.USER_SERVICE_FILE);
var responseUtil = require(constant.RESPONSE_UTIL_FILE);
module.exports = function(app) {
app.use(constant.USER_PATH, router); // constant.USER_PATH is '/user' (added after alexmac asked)
**// this works**
app.get('/test', function(req, res) {
res.write('hello');
res.end();
});
**// This doesn't work**
router.get('/test', function(req, res) {
res.write('hello');
res.end();
});
};
/*
GET: /user
*/
router.route('/:page?/limit?/:limit')
.get(function(req, res) {
responseUtil.sendResponse(service.allRecords(req, res), req, res);
});
/*
POST: /user
*/
router.route('/')
.post(function(req, res) {
responseUtil.sendResponse(service.saveRecord(req, res), req, res);
});
/*
GET: /user/1
PUT: /user/1
DELETE: /user/1
*/
router.route('/:id')
.get(function(req, res) {
responseUtil.sendResponse(service.findRecord(req, res), req, res);
})
.delete(function(req, res) {
responseUtil.sendResponse(service.deleteRecord(req, res), req, res);
})
.put(function(req, res) {
responseUtil.sendResponse(service.updateRecord(req, res), req, res);
});
These are the key lines. I've changed the order to try to clarify the intent but that shouldn't change how they behave:
// Create a route for GET /test
app.get('/test', function(req, res) {
res.write('hello');
res.end();
});
// Create a route for GET /user/test
router.get('/test', function(req, res) {
res.write('hello');
res.end();
});
app.use('/user', router);
The router is mounted at the path /user so any paths on the router will be relative to /user. In other words, if app is handling requests at http://localhost/test then router will handle http://localhost/user/test.
Change your code with this piece of code
var express = require('express');
var bodyParser = require('body-parser');
var router = express.Router();
router.use(bodyParser.json());
var app = express();
router.get('/test', function(req, res) {
res.write('hello');
res.end();
});
app.use('/route',router);
module.exports = router;
When you want to get use http://localhost:port/route/test
Hope this helps.

Why I still get the "Cannot POST" message?

I have a very simple html form, and express server, but I can't make the routing work. I always get "Cannot Post" message. What did I miss?
var express = require('express');
var bodyparser = require('body-parser');
var path = require('path');
var app = express();
app.use(express.static("public"));
app.use(express.bodyParser());
app.get("/", function(req, res){
res.sendFile(path.join(__dirname+"/index.html"));
});
app.post("/sendform", function(req, res){
res.send('You sent the name "' + req.query.user + '".');
});
app.listen(3000, function(){
console.log("Server is running at port: 3000");
});
<form method="post" action="http://localhost:3000/sendform">
<input type="text" name="username" />
<input type="submit" value="küldés" />
</form>
With express 4.15.3, you have to use the body parser a bit differently.
I changed your code to this and I was able to post to it:
var express = require('express');
var bodyParser = require('body-parser');
var path = require('path');
var app = express();
app.use(express.static("public"));
//app.use(express.bodyParser());
app.use(bodyParser.json({
limit: "10mb"
}));
app.use(bodyParser.urlencoded({
limit: "10mb",
extended: true
}));
app.get("/", function (req, res) {
res.sendFile(path.join(__dirname + "/index.html"));
});
app.post("/sendform", function (req, res) {
res.send('You sent the name "' + req.query.user + '".');
});
app.listen(3000, function () {
console.log("Server is running at port: 3000");
});

Cannot POST form node.js - express

Using express 3.1.0 I have a super simple form:
<form action="/signup" method="post">
<div>
<label>Username:</label>
<input type="text" name="username"/><br/>
</div>
<div>
<label>Password:</label>
<input type="password" name="password"/>
</div>
<div><input type="submit" value="Sign Up"/></div>
</form>
and in the app.js:
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, fs = require('fs')
, User = require('./models/User.js')
, user = require('./routes/user')
, http = require('http')
, path = require('path');
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get('/', routes.index);
app.get('/form', function(req, res) {
fs.readFile('./form.html', function(error, content) {
if (error) {
res.writeHead(500);
res.end();
}
else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(content, 'utf-8');
}
});
});
app.post('/signup', function(req, res) {
var username = req.body.username;
var password = req.body.password;
User.addUser(username, password, function(err, user) {
if (err) throw err;
res.redirect('/form');
});
});
app.get('/users', user.list);
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
when trying to post this form i'm getting:
Cannot POST /signup
and in the console:
"NetworkError: 404 Not Found - http://localhost:3000/signup"
what am i missing here?
Your example works for me. I removed the references to User, user, and routes so that I can run it and the HTTP POST is received and displayed correctly in the console.
app.post('/signup', function(req, res) {
var username = req.body.username;
var password = req.body.password;
console.log("post received: %s %s", username, password);
});
I suspect the error is in your User.addUser() code.
router.route('/signup')
// (accessed at POST http://localhost:3000/api/signup)
.post(function(req, res) {
var username = req.body.username;
var password = req.body.password;
res.json(
{
message: 'signup success',
username : username,
password : password,
}
);
})
.get(function(req,res){
res.json({message: 'get request from signup'});
});
// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);
You can write something like this:
action="http://localhost:3000/sin"

Resources