I want to post some data to server. The problem is that, it seems the server cannot receive the data.
So my post data is like this:
name=hello&email=there&message=sometext
and my server code is like this:
var url = require('url'),
express = require('express'),
http=require('http'),
path = require('path'),
nodemailer = require('nodemailer');
var app = express();
var server = http.createServer(app);
app.engine('.html', require('ejs').__express);
app.set('views', __dirname + '/views');
app.set('view engine', 'html');
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res){
res.render('home');
});
app.use(express.bodyParser());
app.post('/', function(req, response){
console.log(req.body);
// console.log(request.body.name);
});
server.listen(4000);
console.log('server running ' + 'now ' + Date.now());
when the console.log(reg.body) run, the terminal output is "undefined"
All query strings output are parsed by default by app.use(express.bodyParser());.. simple solution to your problem is try logging req.query , something like
console.log(req.query);
move app.use(express.bodyParser())); ahead of app.use(express.static(path.join(__dirname, 'public')));
Related
I've been trying to do a route in Express. For example one /about route, but it doesn't work.
var express = require('express');
var app = express();
var router = express.Router();
var moment = require('moment');
var bodyParser = require('body-parser');
var multer = require('multer'); // v1.0.5
var upload = multer(); // for parsing multipart/form-data
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.get('/', function (req, res) {
//some action
});
app.get('/time', function (req, res) {
//...
});
app.get('/about', function (req, res) {
res.send('about');
});
Currently after calling url/about I'm getting Cannot GET /about as a return and after some research I've got no idea how to resolve this issue. They even describe it that way in the official express docs.
Thank you in advance.
You have something like this in your code? :
app.listen(SERVER_PORT, function () {
console.log("Server successfully started on port:" + SERVER_PORT); });
We should have something like this:
var express = require('express');
var routes = require('./routes');
var http = require('http');
var path = require('path');
const app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/about', routes.about);
and also in the views folder: about.jade
Hi I am trying display the message : respond with a resource from routes folder/user.js
exports.list = function (req, res) {
res.send("respond with a resource");
};
But I am getting an error 404 in command prompt.And in url
localhost:8080\user where the response is sent I get the message:
Cannot GET /user
my app.js has code:
var express = require('express');
var routes = require('./routes');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
http.createServer(app).listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
The example I am working on is from https://www.youtube.com/watch?v=czmulJ9NBP0. and time is at 1.37.41
Your route is named /users not /user. So try navigating to /users in your browser instead and it should work.
i'm trying to use Mongo-Express to lookup my mongoDB, I newbee, after i went under the user and pass i got error -> Cannot GET /
var express = require('express')
, routes = require('./routes')
, http = require('http');
var _ = require('underscore');
var async = require('async');
var utils = require('./utils');
var mongodb = require('mongodb');
var cons = require('consolidate');
var swig = require('swig');
var swigFilters = require('./filters');
var app = express();
var config = require('./config');
//Set up swig
app.engine('html', cons.swig);
Object.keys(swigFilters).forEach(function (name) {
swig.setFilter(name, swigFilters[name]);
});
//App configuration
app.configure(function(){
if(config.useBasicAuth){
app.use(express.basicAuth(config.basicAuth.username, config.basicAuth.password));
}
app.set('views', __dirname + '/views');
app.set('view engine', 'html');
app.set('view options', {layout: false});
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(config.site.baseUrl,express.static(__dirname + '/public'));
app.use(express.bodyParser());
app.use(express.cookieParser(config.site.cookieSecret));
app.use(express.session({
secret: config.site.sessionSecret,
key: config.site.cookieKeyName
}));
app.use(express.methodOverride());
app.use(app.router);
});
First of all, try to learn from actual/updated tutorials. Actual express version is 4, and it removes:
app.use(app.router);
(therefore my deduction of outdated tutorial)
Second thing, i dont see in your code any routes. If you want to get responses from server, you need to write routes. For example:
app.get('/test', function(req, res) {
res.send('Hello from route');
});
I'v got express app like this.
var express = require('express');
var http = require('http');
var path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(app.router);
app.get('*', function(res,req) {
req.render('index', {title: "Title"});
});
http.createServer(app).listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
Because of using app.get('*') request to not existent static files responses with rendered index.ejs file instead of error 404.
Is there any way to fix it without additional conditions in routes?
Just add something like:
app.get(/\/(js|css|img)\/.*/, function (req, res) {
res.send(404);
});
before app.get('*'). Any request to /js that wasn't already matched by the static middleware references an file that does not exist.
Resolved problem by nginx proxying
I have written a code snippet using backbone which POST's data to the urlRoute .
(function(){
"use strict"
window.Course = Backbone.Model.extend({
defaults:{
title:''
},
urlRoot:"courses/"
});
var courses = new Course({title:"Sending a Post request to the node-express backend,but how to access this in the backend"});
courses.save();
})();
I have used node.js - express framework in the backend ,i want to know how to retrieve the value of the title attribute using the app.post('/courses',function(req,res){}) method .
This is the node.js backend ,The control comes to the app.post method , but just want ot how to the access the model value in the posted data .
var express = require('express')
, routes = require('./routes')
, 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.post('/courses',function(req,res) {
console.log('Request successfully recieved');
console.log("how do i get the posted data here !!");
});
app.get('/', routes.index);
app.get('/users', user.list);
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
You can find your request data in req.body (more on that http://expressjs.com/api.html#req.body).
In your case you can do like this:
app.post('/courses',function(req,res) {
console.log(req.body.title);
});