Giter VIP home page Giter VIP logo

Comments (4)

dougwilson avatar dougwilson commented on May 2, 2024

It's no problem. So continuing, the reason is because you are not using some of those libraries correctly. For instance, that message is because app.use(bodyParser.urlencoded()) needs to be app.use(bodyParser.urlencoded({ extended: true })) according to that module's documentation.

from generator.

freealex avatar freealex commented on May 2, 2024

@dougwilson ok I added that along with bodyParser.json & sookieParser. I'm not sure if that's what you meant to do, so I've been reading the API documentation but now its thowing
TypeError: undefined is not a function
Accompanied with the same locations. I feel like I'm missing something big here, and I don't want to make you walk me through this step by step. But if you have another idea based off of that or where I showed look to move this forward; like a good starting point for a decent java/web dev but with just starting with cmd, would be great. I'll give you a break after this next suggestion because I have a paper I need to writ. This code style is just addicting once you get started with it!

from generator.

dougwilson avatar dougwilson commented on May 2, 2024

Hi, sorry, @ADC5 , do you still need help? If so, can you post the corresponding source as well as the error with it's full stack trace?

from generator.

freealex avatar freealex commented on May 2, 2024

Hi Christopher,
Thanks for responding to me!  The issue that I'm having is that I can't get my app to connect to my mongo db.  I'm going to paste each of my pages in this:
app.js:

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
/// catch 404 and forwarding to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

module.exports = app;

#!/usr/bin/env node
/** * Module dependencies. /
var app = require('../app');var debug = require('debug')('nodetest3:server');var http = require('http');
/
* * Get port from environment and store in Express. */
var port = normalizePort(process.env.PORT || '3000');

var express = require('express'),    http = require('http');
var app = express();
var express = require('express'),    http = require('http');
var app = express();//http.createServer(app).listen(port);http.createServer(app).listen(port);//try with line 30 commentedhttp.createServer(app).listen(port);http.createServer(app).listen(port);
/** * Create HTTP server. /
/var server = http.createServer(app);*/
/** * Listen on provided port, on all network interfaces. /
server.listen(port);server.on('error', onError);server.on('listening', onListening);
/
 _ Normalize a port into a number, string, or false. /
function normalizePort(val) {  var port = parseInt(val, 10);
  if (isNaN(port)) {    // named pipe    return val;  }
  if (port >= 0) {    // port number    return port;  }
  return false;}
/
 _ Event listener for HTTP server "error" event. /
function onError(error) {  if (error.syscall !== 'listen') {    throw error;  }
  var bind = typeof port === 'string'    ? 'Pipe ' + port    : 'Port ' + port;
  // handle specific listen errors with friendly messages  switch (error.code) {    case 'EACCES':      console.error(bind + ' requires elevated privileges');      process.exit(1);      break;    case 'EADDRINUSE':      console.error(bind + ' is already in use');      process.exit(1);      break;    default:      throw error;  }}
/
_ _ Event listener for HTTP server "listening" event. /
function onListening() {  var addr = server.address();  var bind = typeof addr === 'string'    ? 'pipe ' + addr    : 'port ' + addr.port;  debug('Listening on ' + bind);}
<-----------------------users.js----->var express = require('express');var router = express.Router();
/
GET users listing. /router.get('/', function(req, res, next) {  res.send('respond with a resource');});
module.exports = router;
/
 * POST to adduser. */router.post('/adduser', function(req, res) {    var db = req.db;    db.collection('userlist').insert(req.body, function(err, result){        res.send(            (err === null) ? { msg: '' } : { msg: err }        );    });})<------------------global.js-------------------->

// Userlist data array for filling in info boxvar userListData = [];
// DOM Ready =============================================================$(document).ready(function() {
    // Populate the user table on initial page load    populateTable();     // Username link click    $('#userList table tbody').on('click', 'td a.linkshowuser', showUserInfo);     // Add User button click    $('#btnAddUser').on('click', addUser);
});
// Functions =============================================================
// Fill table with datafunction populateTable() {
    // Empty content string    var tableContent = '';
    // jQuery AJAX call for JSON    $.getJSON( '/users/userlist', function( data ) { //adds data from db to populate the app userListData = data;         // For each item in our JSON, add a table row and cells to the content string        $.each(data, function(){            tableContent += '';            tableContent += '' + this.username + '';            tableContent += '' + this.email + '';            tableContent += 'delete';            tableContent += '';        });
        // Inject the whole content string into our existing HTML table        $('#userList table tbody').html(tableContent);    });};

function showUserInfo(event) {
    // Prevent Link from Firing    event.preventDefault();
    // Retrieve username from link rel attribute    var thisUserName = $(this).attr('rel');
    // Get Index of object based on id value    var arrayPosition = userListData.map(function(arrayItem) { return arrayItem.username; }).indexOf(thisUserName);
    // Get our User Object    var thisUserObject = userListData[arrayPosition];
    //Populate Info Box    $('#userInfoName').text(thisUserObject.fullname);    $('#userInfoAge').text(thisUserObject.age);    $('#userInfoGender').text(thisUserObject.gender);    $('#userInfoLocation').text(thisUserObject.location);
};
// Add Userfunction addUser(event) {    event.preventDefault();
    // Super basic validation - increase errorCount variable if any fields are blank    var errorCount = 0;    $('#addUser input').each(function(index, val) {        if($(this).val() === '') { errorCount++; }    });
    // Check and make sure errorCount's still at zero    if(errorCount === 0) {
        // If it is, compile all user info into one object        var newUser = {            'username': $('#addUser fieldset input#inputUserName').val(),            'email': $('#addUser fieldset input#inputUserEmail').val(),            'fullname': $('#addUser fieldset input#inputUserFullname').val(),            'age': $('#addUser fieldset input#inputUserAge').val(),            'location': $('#addUser fieldset input#inputUserLocation').val(),            'gender': $('#addUser fieldset input#inputUserGender').val()        }
        // Use AJAX to post the object to our adduser service        $.ajax({            type: 'POST',            data: newUser,            url: '/users/adduser',            dataType: 'JSON'        }).done(function( response ) {
            // Check for successful (blank) response            if (response.msg === '') {
                // Clear the form inputs                $('#addUser fieldset input').val('');
                // Update the table                populateTable();
            }            else {
                // If something goes wrong, alert the error message that our service returned                alert('Error: ' + response.msg);
            }        });    }    else {        // If errorCount is more than 0, error out        alert('Please fill in all fields');        return false;    }}; /*
As you can see, we're using a global variable and definingour functions at the top level. This is actually not a greatidea and I'm only doing it for speed and simplicity. In a real app, you want to define a single master global, which you canthen populate with properties, methods, etc … as needed, thus helping to avoid conflicts or generally pollute the namespace. If you want to learn more about this strategy, I strongly recommendpicking up a copy of "JavaScript: The Good Part"
/<--------------package.json------------------->
{  "name": "project1",  "version": "0.0.0",  "private": true,  "scripts": {    "start": "node ./bin/www"  },  "dependencies": {    "body-parser": "~1.12.0",    "cookie-parser": "~1.3.4",    "debug": "~2.1.1",    "express": "~4.12.2",    "jade": "~1.9.2",    "morgan": "~1.5.1",    "mongodb": "
",      "monk": "",  "mongo": "",    "serve-favicon": "~2.2.0" "string_decoder": "~0.10.x      "morgan":"~1.5.1"  }}
I saw the update for this part, but it throws an  error when I try to add "mongoskin": "`1.4.0"
My layout, index.jade seems to be replicating perfectly, but I'll include them just in case-->:<---------------------------index.jade-------------------->
extends layout
block content    h1= title    p Welcome to our test
    // Wrapper    #wrapper
        // USER INFO        #userInfo            h2 User Info            p                strong Name:                |                  br                strong Age:                |                  br                strong Gender:                |                  br                strong Location:                |          // /USER INFO
        // USER LIST        h2 User List        #userList            table                thead                    th UserName                    th Email                    th Delete?                tbody        // /USER LIST         // ADD USER        h2 Add User        #addUser            fieldset                input#inputUserName(type='text', placeholder='Username')                input#inputUserEmail(type='text', placeholder='Email')                br                input#inputUserFullname(type='text', placeholder='Full Name')                input#inputUserAge(type='text', placeholder='Age')                br                input#inputUserLocation(type='text', placeholder='Location')                input#inputUserGender(type='text', placeholder='gender')                br                button#btnAddUser Add User        // /ADD USER     // /WRAPPER
<--END-->
<--style.css-->
body {  padding: 30px;  font: 14px "Lucida Grande", Helvetica, Arial, sans-serif;}
h2 { margin:0 0 .5em 0;}
a {  color: #00B7FF;}
#wrapper { padding-left:312px; position:relative;}
#userList { margin:0 0 30px 0;} #userList table { border-collapse:separate; border-spacing:1px; background:#CCC; } #userList table th { background:#EEE; font-weight:600; padding:10px 20px; text-align:center; } #userList table tbody { padding:0; margin:0; border-collapse:collapse; border-spacing:0px; } #userList table td { background:#FFF; padding:5px 10px; text-align:center; }
#userInfo { width:250px; position:absolute; top:0; left:0;} #userInfo p { padding:15px; border:1px solid #CCC; background:rgba(80,120,255,0.05); }
fieldset { border:0; padding:0; margin:0;}
<----end style.css---->
This how I've been trying to connect my db (after mkdir data, path: c:\node\nodetest3\data ->
'mongod --dbpath c:\node\nodetest3\data'
I have  the mongo.exe files save in c:\mongo\ and the app files save in  "c:\node\nodetest3", the data file is created in here and I followed the directions for creating the database and am able to retrieve the data just fine but it's not posting to the page when I enter 'loaclhost:3000' into my browser.  It shows everything else perfectly though, so I'm assuming (could be wrong as an amateur to be making this assumption) that this is the issue.  back to the issue, so I can start the app with 'npm start' and see it perfectly.I've tried opening the mongo shell then: c:\mongo> mongoMongoDB shell version 3.0.3>use nodetst3switched d to nodetest3'fullname>db.userlist.insert({'username' : 'alex','email' :[email protected]','fullname' : 'alex carl','age' : '26','location' : 'Seattle','gender' : 'male'})WriteResults({ "nInserted" : 1 })>
I don't remember the call off the top of my head ,but when I then search the db using anyone of these vatibles and it's value, it returns the whole user summary.  I'm so close that I can taste t and would greatly appreciate if you can help get this connected.  Ultimately I want to try to use this to try and create an app for the DCenter (disability rights center) at my college (UW Seattle).  I really love to program and I somehow came across this page and am so thankful for that fact, because I love learning/using all the aspects of node.js.  Ok, now I'll add the error messages, but I'm not sure if it's actually throwing any, because it is running, just doesn't have any of the data included on the page. 
In my c:\node folder i have: (folder):bin    -www
    -www.txt
(folder):data    -tmp
        (empty)
    -journal
            -j._0
            -lsn
(folder):node_modules    -.bin
    -git-cli
    -module
    -mongoose
    -mysql    -passport
    -semver            -strongloop

(folder):public    -images
        -images_app.js
    -javascripts
        -global.js
    -stylesheets
        -style.css
(folder):routes    -index.js
    -users.js
(folder):views    -error.jade    -index.jade
    -layout.jade
[a weird file that says 3.3.4' file without an icon just, I think it's the express version] app.jslayout.jadenpm-debug.logpackage.json
<--end of dir - filepaths-->

c:\node\nodetest3\npm-debug.log:
0 info it worked if it ends with ok
1 verbose cli [ 'C:\Program Files\nodejs\node.exe',
1 verbose cli   'C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js',
1 verbose cli   'start' ]
2 info using [email protected]
3 info using [email protected]
4 verbose node symlink C:\Program Files\nodejs\node.exe
5 verbose run-script [ 'prestart', 'start', 'poststart' ]
6 info prestart [email protected]
7 info start [email protected]
8 verbose unsafe-perm in lifecycle true
9 info [email protected] Failed to exec start script
10 verbose stack Error: [email protected] start: node ./bin/www
10 verbose stack Exit status 1
10 verbose stack     at EventEmitter. (C:\Program Files\nodejs\node_modules\npm\lib\utils\lifecycle.js:213:16)
10 verbose stack     at EventEmitter.emit (events.js:110:17)
10 verbose stack     at ChildProcess. (C:\Program Files\nodejs\node_modules\npm\lib\utils\spawn.js:14:12)
10 verbose stack     at ChildProcess.emit (events.js:110:17)
10 verbose stack     at maybeClose (child_process.js:1015:16)
10 verbose stack     at Process.ChildProcess._handle.onexit (child_process.js:1087:5)
11 verbose pkgid [email protected]
12 verbose cwd c:\node\nodetest3
13 error Windows_NT 6.3.9600
14 error argv "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js" "start"
15 error node v0.12.2
16 error npm  v2.7.4
17 error code ELIFECYCLE
18 error [email protected] start: node ./bin/www
18 error Exit status 1
19 error Failed at the [email protected] start script 'node ./bin/www'.
19 error This is most likely a problem with the nodetest3 package,
19 error not with npm itself.
19 error Tell the author that this fails on your system:
19 error     node ./bin/www19 error You can get their info via:
19 error     npm owner ls nodetest3
19 error There is likely additional logging output above.
20 verbose exit [ 1, true ]
**I'm also only at the db craetion step if that wasn't clear. 
I'll post this to the page forum right after this.  Thanks again for creating this tutorial, and especially for the help you offer everyone that's interested!
Thanks!Alex Carl

from generator.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.