I've got a small node.js application using the express framework, but for some reason I can't get my application to respond to POST requests. In the server log I simply get "POST / 404 5ms", and I can't figure out why.
EDIT: To clarify - My problem is that app.post doesn't seem to be doing anything
EDIT 2: I somehow managed to fix this last night, but now I can't figure out at what point i fixed it.
Node.js server code:
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path');
var app = express();
// all environments
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(express.cookieParser('chocolatechip'));
app.use(express.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
//pages
//Landing page
app.get('/', routes.index);
app.post('/test',function(req,res){
console.log(req.body);
res.send("received post");
});
//return list containing users
//app.post('/users', user.list);
//return requested user
app.get('/users/:id', user.get);
//app.post('/users/login', user.login);
//server
http.createServer(app).listen(app.get('port'), function(){
console.log('Server listening on port ' + app.get('port'));
});
On the actual webpage, I've got the following javascript code:
var login = $('#login');
var page = $('#page');
var register = $('#register');
var userField = login.find('.user');
var passField = login.find('.pass');
var confPassField = login.find('.confpass');
var form = $('.logform');
$('#formbutton').on('click',function(){
if(register.hasClass('hidden')){
login.addClass('hidden');
confPassField.val('');
var logDat = JSON.stringify(form.serializeArray);
userField.val('');
passField.val('');
page.html("Login form submitted");
$.post(
form.attr("action"),
{test:"test"},
function(data){
alert("Response: "+data)
}
);
}
If you are posting to / as your log is saying that you are "POST / 404 5ms", you need to change the following line:
app.get('/', routes.index);
to
app.all('/', routes.index);
This will allow a GET or POST to that route. You can also just use app.post() if you are only posting to that route. Hope this helps.
Docs here: http://expressjs.com/api.html#app.all
Make sure that 'form.attr("action")' is getting the proper URL. It seems that your form is posting to the index page rather than to '/test'. Maybe that should be changed to $('form').attr("action")
For me the problem was that I had my
app.post('/test', jsonParser, function (req, res) {
console.log(req);
res.send('Ok');
});
below this part added by express-generator to my app.js
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
By changing the order in the file I resolved this problem.
Related
can't seem to figure out what the problem with my file structure might be. I'm using Aurelia as a front end and node for the server. I did a join that fixed some of the issues but now I'm getting this error:
Error: (SystemJS) Error: XHR error (404 Not Found) loading http://localhost:3000/src/main.js
Error loading http://localhost:3000/src/main.js
This is my server.js file:
var express = require('express'),
app = express(),
engines = require('consolidate'),
MongoClient = require('mongodb').MongoClient,
assert = require('assert'),
bodyParser = require('body-parser');
app.engine('html', engines.nunjucks);
app.set('view engine', 'html');
app.set('views', __dirname + '/views');
app.use(bodyParser.urlencoded({ useNewUrlParser: true }));
app.use('/scripts', express.static(require('path').join(__dirname, 'scripts')));
function errorHandler(err, req, res, next) {
console.log(err.message);
console.log(err.stack);
res.status(500).render('error_template', {err: err});
}
MongoClient.connect('mongodb://localhost:27017/', function(err, client) {
assert.equal(null, err);
console.log('MongoDB connected!')
var db = client.db('todos');
app.get('/', function(req, res) {
res.render('index', {});
});
app.use(errorHandler);
});
var server = app.listen(3000, function() {
var port = server.address().port;
console.log("Express server listening on port %s.", port);
});
app.use('/scripts', express.static(require('path').join(__dirname, 'scripts')));
This line of code takes a local folder and makes it available through the express server. You need to do the same thing for your src folder
either with:
app.use('/src', express.static(require('path').join(__dirname, 'src')));
or:
app.use(express.static(require('path').join(__dirname, 'src')));
the first parameter allows you to name the directory it will be served as, which is usually the same.
And even though I didn't include the require('path').join(__dirname,... in the comment, it's good practice to include it.
I saved email in session in my login.js
router.get('/signin',function(req,res,next) {
res.send(req.session.email);//here i can get email from session as well
console.log("email inside ./signin in login.js "+req.session.email);
});
router.post('/login', function(req, res) {
req.session.email=req.body.email; //get email from form body
console.log(req.session.email); // here i can get my email in console
res.redirect('/') //want to redirect to home
});
I want to access email from session in my index.js
var session;
router.get('/', function(req, res, next) {
session=req.session;
console.log("your mail is"+session.email);
});
And this is app.js config
var
express = require('express');
var app = express();
var path = require('path');
var connection=require('./models/connection');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session=require('express-session');
var index = require('./routes/index');
var users = require('./routes/users');
var login=require('./routes/login');
var debug = require("debug");
var clc = require('cli-color');
var router=express.Router();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(favicon(path.join(__dirname, 'public/images/', 'favicon.gif')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser("secretkey"));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/assets', express.static(__dirname + '/assets'));
app.use(session({secret: 'secretkey',saveUninitialized: true,resave: true}));
app.get('/login',login);
app.post('/login',login);
app.get('/signin',login);
app.get('/',index);
module.exports = app;
Want some thing like this we can do in php
<!-- first page -->
<?php
session_start();
$_SESSION['myvar'] = 'hello';
?>
<!-- second page -->
<?php
session_start();
echo $_SESSION['myvar']; // it will print hello
?>
I tried these and some more answer but none of them solve my problem
NodeJS express-session req.session is undefined
req.session is undefined in Node?
How to use req.session data in an other javascript file expressjs
So, I tried your code as-is as best I could (copied and pasted from yours, added files that were needed that you didn't post here, e.g. a server.js file that actually starts listening on a port), and it worked as-is with just one change.
Your index.js file does not ever actually send anything back to the client. Note your code:
var session;
router.get('/', function(req, res, next) {
session=req.session;
console.log("your mail is"+session.email);
});
There's no res.send or res.render called, so it's going to just hang. It has nothing to do with the session value, though, the console.log statement still prints out the correct email value that was posted before.
Try:
var session;
router.get('/', function(req, res, next) {
session=req.session;
console.log("your mail is"+session.email);
res.send(session.email);
});
Ok, so I'm new to Express. I'm messing around with sessions and ajax calls, but the problem I'm having is that whenever I run my app, my jquery doesn't work for some reason. This is the code I have:
app.js
var express = require("express");
var mongoose = require("mongoose");
var bodyParser = require("body-parser");
var session = require('express-session')
var app = express();
app.use(express.static("public")); // I understand this is the directory where I would need to put all my static files: css, js, images, etc.
app.set("view engine", "jade");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
//Set secre pass for the session
app.use(session({secret:'password'}));
app.get("/",function(req, res){
if(req.session.userName){
res.render("admin", {session_name: req.session.userName});
}else{
res.render("home");
}
});
app.post("/example-ajax", function(req, res){
res.send(req.body.email); // return the email that was sent by the client
});
app.post("/log-in", function(req, res){
req.session.userName = req.body.name;
res.redirect("/");
});
app.get("/log-out", function(req, res){
req.session.destroy();
res.redirect("/");
});
app.listen(8080);
admin.jade
extends layout_head.jade
block content
div(class="container")
div(class="row")
div(class="col-lg-6 col-lg-offset-3")
h1 Logged In!!
h3 Logged in as: #[b #{session_name}]
a(href="/log-out") Log Out
br
div(class="btn btn-info testAjax") Test Ajax
script(src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js")
script(href="/css/bootstrap/js/bootstrap.min.js")
script(href="/js/main.js")
main.js
$(document).ready(function(){
alert("Loaded");
$(".testAjax").on("click", function(){
alert("test");
$.ajax({
type: 'POST',
url: '/example-ajax',
data: {
email: "admin#yahoo.com"
},
success: function(data){
// data = the email being returned from the server
console.log("Your email is: " + data);
}
});
});
});
So like I said, the jquery doesn't run whenever my page loads up or when I click the testAjax button. When I check the console, it doesn't give me any errors so I don't know what is causing the problem.
My second question is: Is this the right way to make ajax calls in Express?
Any help is greatly appreciated. Thanks.
I just needed to change href to src in the script tags.
I'm using node with express#4.13.4 and body-parser#1.13.3.
My jade page has for instance this property:
input(type='text',class='form-control', placeholder="Username", name='username', id="username")
The JavaScript code looks like this:
var bodyParser = require('body-parser');
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path');
var app = express();
var favicon = require('favicon')
app.use(bodyParser.json());
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use( function(req, res, next){
app.locals.pretty = true
next()
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static(path.join(__dirname, 'public')));
app.get('/create', function(req,res) {
res.render("create");
});
app.get('/creation', function(req,res) {
console.log("creation")
console.log(req.body)
});
The create page is the first opened and there is also the input field username, but the request body is empty in the /creation function. Can anyone help ?
You need to submit the form using POST method and alter the function:
app.post('/creation', function(req,res) {
console.log("creation")
console.log(req.body); // here will show the values of inputs submited
});
More about express routes.
As we understood body parse will work on the submit of the form or json with POST request. in this case make sure you are submitting the form correctly, you can see the POST request in firebug or other tool. Once its done correctly you will be able to see the body elements by req.body.username
you can have simple form like.
<form action='post' ..>
<input name='username' ..>
<input type='submit' ..>
</form>
Also I seen two times middleware app.use(bodyParser.json()); use. in case you missed it.
I just try to write a simple node.js application, but if I use the express-validator the site is just loading and do nothing :(
"waiting on localhost", after some time an "ERR_EMPTY_RESPONSE" error appears.
If i delete the app.use(expressValidator) the application works again.
var express = require('express'),
expressValidator = require("express-validator");
var app = express();
app.configure(function(){
app.set('view engine', 'jade');
app.set('views', __dirname + '/views');
app.use(express.bodyParser());
app.use(expressValidator);
});
app.get('/', function(req, res) {
console.log('get something get');
res.render('app.jade');
});
app.post('/', function(req, res){
console.log('get something post');
res.render('app.jade');
});
app.listen(process.env.PORT || 8080);
You need to call the expressValidator function to get it to return a middleware handler:
app.use(expressValidator());
^^ important!