Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var express = require('express');
- var app = express();
- var bodyParser = require('body-parser');
- var mongoose = require('mongoose');
- var Name = require('./Name.model');
- var bootstrap = `<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>`;
- // 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(`
- ${bootstrap}
- <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.writeHead(200, {'Content-type': 'text/html'});
- res.write(` ${bootstrap}
- <style>
- table {
- margin: 1em auto;
- width: 25%;
- }
- #table {
- text-align: center;
- }
- td, th {
- border: 1px solid #dddddd;
- text-align: left;
- padding: 8px;
- }
- tr:nth-child(even) {
- background-color: #dddddd;
- }
- </style>
- <div id='table'>
- <table>
- <tr>
- <th>name</th>
- <th>age</th>
- </tr>
- `)
- names.forEach(function(n) {
- if(n.name){
- res.write(` <tr>
- <td>${n.name}</td>
- <td>${n.age}</td>
- </tr>`);
- }
- });
- res.write(`</table><br />
- <a href='/'>Home</a></div>`)
- res.end();
- }
- });
- });
- 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.redirect('/names');
- }
- });
- });
- app.listen(port, function() {
- console.log('Listening on port 8080');
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement