Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Here is the code for the app
- //app.js
- var express = require('express');
- var app = express();
- var bodyParser = require('body-parser');
- var mongoose = require('mongoose');
- var Name = require('./Name.model');
- // parse application/x-www-form-urlencoded
- app.use(bodyParser.urlencoded({ extended: true }))
- // parse application/json
- app.use(bodyParser.json())
- var db = 'mongodb://test:test@ds135577.mlab.com:35577/nodepractice';
- mongoose.connect(db);
- var port = 8080;
- app.get('/', function(req,res) {
- res.send(`
- <head>
- <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
- </head>
- <style>
- #form {
- text-align: center
- }
- </style>
- <body>
- <div id="form">
- <form action='/name' method='post'>
- <h2>name:</h2>
- <input type="text" name="name">
- <br/>
- <h2>age:</h2>
- <input type="age" name="age">
- <br/><br/>
- <input type="submit" value="submit">
- </form>
- </div>
- <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
- </body>
- `);
- });
- app.get('/names', function(req,res) {
- Name.find({})
- .exec(function(err,names) {
- if (err) {
- res.send('An error has occured');
- } else {
- res.json(names);
- }
- });
- });
- app.post('/name', function(req,res) {
- var newName = new Name();
- newName.name = req.body.name;
- newName.age = req.body.age;
- newName.save(function(err, name) {
- if (err) {
- res.send('error: ${err}');
- } else {
- console.log(name);
- res.send(name);
- }
- });
- });
- app.listen(port, function() {
- console.log('Listening on port 8080');
- });
- //Here is the code for the db schema
- //Name.model.js
- var mongoose = require('mongoose');
- var Schema = mongoose.Schema;
- var nameSchema = new Schema({
- name : String,
- age : Number
- });
- module.exports = mongoose.model('name', nameSchema);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement