Instagram real-time api - real-time

I'm trying to use Instagram real-time api but I can't make it work. I created an express.js server that responds to challenge verification on subscription creation. I get a json response with my subscription details and I can list my current subscriptions from Instagram API.
Everything works ... except I don't get a POST request. Any idea?
Regards!

var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var request = require('request');
var bodyParser = require('body-parser');
app.use(bodyParser.json());
var CLIENT_ID ='';
var CLIENT_SECRET = '';
var CALLBACK_URL = 'http://website.com/subscribe';
app.get('/:object/:object_id', function (req, res) {
var object = req.params.object;
var object_id = req.params.object_id;
io.on('connection', function (socket) {
request.post('https://api.instagram.com/v1/subscriptions/', {form: {
client_id: CLIENT_ID,
client_secret: CLIENT_SECRET,
aspect: 'media',
object: object,
object_id: object_id,
callback_url: CALLBACK_URL
}});
socket.on('disconnect', function() {
request.del('https://api.instagram.com/v1/subscriptions?client_secret='+CLIENT_SECRET+'&object=all&client_id='+CLIENT_ID)
});
});
res.sendFile(__dirname + '/public/index.html');
})
app.get('/subscribe', function(req, res){
res.send(req.query['hub.challenge']);
});
app.post('/subscribe', function (req, res) {
io.emit('message', JSON.stringify(req.body));
})
http.listen(process.env.PORT);
index.html
<!doctype html>
<html>
<head>
<title>htag</title>
</head>
<body>
<div id="stream"></div>
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="https://cdn.socket.io/socket.io-1.3.4.js"></script>
<script>
var socket = io(window.location.origin);
socket.on('message', function (text) {
$('#stream').prepend('<p>' + text);
});
</script>
</body>
</html>

Related

Trying to post data via html-form and JavaScript to RESTapi – gets 404 Cannot Post?

I have googled a lot, gone through a lot of questions but can't find an answer.
I have built a simple RESTapi with node and mongoDB, using express and mongoose. The database is hosted on Atlas. The RESTapi works fine when accessing with postman, no problem there.
To access and use the RESTapi via the site I get the GET and DELETE method to work, but when trying to post data with a form I get the error “Cannot Post/ 404”. I have tried a lot of things but can´t get it to work. (I don't know it it is related, but the content-security policies which makes some scripts don't load, I have tried to allow everything in the head meta-info in index.html, but it doesn't make a change)
Request headers
Accept
text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding
gzip, deflate
Accept-Language
en-US,en;q=0.5
Cache-Control
no-cache
Connection
keep-alive
Content-Length
530
Content-Type
multipart/form-data; boundary=---------------------------52045656921129358052645853016
Host
localhost:3000
Origin
http://localhost:3000
Pragma
no-cache
Referer
http://localhost:3000/
Upgrade-Insecure-Requests
1
The RESTapi and the site accessing is in the same folder, here is the project structure:
Here is the code:
js/main.js
window.onload = loadCourses();
// Variebles from the form
let formCreate = document.getElementById("formCreate");
let courseIdIn = document.getElementById("courseId");
let courseNameIn = document.getElementById("courseName");
let coursePeriodIn = document.getElementById("coursePeriod");
let message_form = document.getElementById("message_form");
const myForm = document.getElementById('formCreate');
myForm.addEventListener('submit', (e) => {
console.log('Hello from eventlistner');
e.preventDefault();
addCourse();
})
// GET courses
function loadCourses() {
$.getJSON("http://localhost:3000/courses", function(data) {
//rensa listan
console.log(data);
$("#tbody").html("");
for(let i = 0; i<data.length; i++) {
$("tbody").append("<tr><td>" + data[i]._id + "</td>" + "<td>"+ data[i].courseId + "</td>" + "<td>" + data[i].courseName +
"</td>" + "<td>" + data[i].coursePeriod + "</td>" + "<td><img class='deleteSize' onclick='deleteCourse(\""+data[i]._id+"\")' src='images/delete-photo.svg'alt='ikon radare'></td></tr>");
}
});
}
// DELETE course
function deleteCourse(id) {
console.log(id)
$.ajax({
type: "DELETE",
url: "http://localhost:3000/courses/" + id
}).done(function(response) {
console.log(response);
//ladda om listan
loadCourses();
});
}
// add course
function addCourse() {
console.log("Hi from add Course");
let courseIdEl = courseIdIn .value;
let courseNameEl = courseNameIn.value;
let coursePeriodEl = coursePeriodIn.value;
let courseObj =
{
"courseId": courseIdEl.value,
"courseName": courseNameEl.value,
"coursePeriod": coursePeriodEl.value
}
console.log(courseObj);
//Skapar fetch-anrop
fetch('http://localhost:3000/courses', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': '*/*',
},
body: JSON.stringify(courseObj)
})
.then(response => response.json())
.then(data => {
// message
let message = data.message;
message_form.innerHTML = message;
//document.getElementById("message_form").innerHTML = message;
loadCourses();
formCreate.reset();
})
.catch(error => {
console.log('Error: ', error);
})
}
the index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Content-Security-policy" content="default-src *;
script-src *;
connect-src *;">
<link rel="stylesheet" href="css/style.css">
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="js/main.js"></script>
<script src="main2.js"></script>
<title>Moment 3 - mongoose.js</title>
</head>
<body>
<h1>Moment 3 - mongoose.js</h1>
<table>
<thead>
<tr>
<th>ID</th>
<th>Kurs</th>
<th>Kursnamn</th>
<th>Period</th>
<th>Radera</th>
</tr>
</thead>
<tbody id="tbody">
<tr>
<td>1</td>
<td>DT162G</td>
<td>JavaScript-basar webbutveckling</td>
<td>1</td>
<td><img class="deleteSize" onclick="deleteCourse()" src="images/delete-photo.svg" alt="ikon radare">
</td>
</tr>
</tbody>
</table>
<h3>Create course:</h3>
<form class="forms" action="" id="formCreate" method="POST" enctype="multipart/form-data">
<!--fält för formulär, hela den grå delen-->
<fieldset id="field">
<p class="pfield" id="message_form"></p>
<label for="courseId">Kurskod:</label><br>
<input type="text" name="courseId" id="courseId" class="input">
<br>
<label for="courseName">Kursnamn:</label><br>
<input type="text" name="courseName" id="courseName" class="input">
<br>
<label for="coursePeriod">Kursperiod:</label><br>
<input type="number" id="coursePeriod" name="coursePeriod" min="1" max="2">
<div class="btn-wrapper">
<button type="submit" name="submitPost" id="btn-create" class="btn btn2">Publish</button>
<button type="reset" name="deletePost" id="btn-reset" class="btn btn2 btn-reset">Delete
field</button>
</div>
</fieldset>
</form>
</body>
</html>
RESTapi code
routes/courses.js
const express = require('express');
const router = express.Router();
// Hämtar schemamodel
const Courses = require('../models/CourseModel');
// Get all courses
router.get('/', async (req, res) => {
try {
const allCourses = await Courses.find();
if(!allCourses) {
throw Error('No items found');
} else {
res.status(200).json(allCourses);
}
} catch(err) {
res.status(500).json( {msg: err})
}
})
// GET one course
router.get('/:id', getCourse, (req, res) => {
res.json(res.course)
})
// Create course
router.post('/', async (req, res) => {
const newCourse = new Courses({
courseName: req.body.courseName,
courseId: req.body.courseId,
coursePeriod: req.body.coursePeriod
});
try {
const course = await newCourse.save();
if(!course) {
throw Error('Something went wrong while saving the post =( ');
} else {
// It worked ok, post is created
res.status(201).json(course);
}
} catch (err) {
// bad input from user = 400
res.status(400).json( {msg: err})
}
});
// UPDATE one course
router.patch('/:id', getCourse, async (req, res) => {
// options new = true makes mangoose send back updated data and not old
let options = { new: true };
try {
const course = await Courses.findByIdAndUpdate(req.params.id, req.body, options);
if(!course) {
throw Error ('Something went wrong while updating the post =( ');
} else {
// It worked ok, post is created
res.json(course).status(201).json( {success: true});
}
} catch {
res.status(400).json( {message: err.message})
}
})
// DELETE one course
router.delete('/:id', getCourse, async (req, res) => {
try {
await res.course.deleteOne();
res.status(200).json( {message: 'Success: Course is deleted!'})
} catch (err){
res.status(503).json( {message: err.message})
}
})
// Creating middlewhere function to re-use, findbyid. Middlewhere idé = webdev simplified
async function getCourse(req, res, next) {
let course;
try {
course = await Courses.findById(req.params.id)
if (course == null) {
return res.status(404).json( {message: 'Cant find any course with that ID'})
}
} catch (err) {
return res.status(500).json( {message: err.message})
}
res.course = course;
next();
}
module.exports = router;
models/CourseModel.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const CourseSchema = new Schema( {
courseName: {
type: String,
required: true
},
courseId: {
type: String,
required: true
},
coursePeriod: {
type: Number,
required: true
}
});
module.exports = mongoose.model('Courses', CourseSchema );
server.js
require('dotenv').config();
const express = require('express');
const app = express();
const path = require("path");
const mongoose = require('mongoose');
//const { MONGO_URI } = require('./config');
// Connect to MongoDB
mongoose.connect(process.env.MONGO_URI,{ useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false })
.then(() => console.log('Connected to Mongo Database.'))
.catch(err => console.log(err));
//BodyParser Middleware, for use of JSON in body
app.use(express.json());
// skapa statisk sökväg
app.use(express.static(path.join(__dirname, 'public')));
// Routes
const courseRoutes = require('./routes/courses.js')
app.use('/courses', courseRoutes)
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log (`Server run at port ${PORT}`));
well, it was a stupid mistake in HTML, the script source tag for the javascript-file main.js was in the head section. Of course, it must be in the bottom just before the body-tag. So stupid of me.

Error 404 Not Found Using Pug & Express and MongoDB

I am getting at 404 not found error using Express & MongoDB for a POST request. I tried to redo my routes numerous times, but am having trouble with the login page. I want to POST the information to my server and render a simple "Welcome Message."
Please advise.
Routes Folder:
var express = require('express');
var router = express.Router();
let mongoose = require('mongoose');
var User = require('../models/users')
//Get registration page from index button//
router.get('/register', function(req, res, next) {
res.render('register');
if (err) return console.error(err);
res.json(user);
});
//Post user data to database POST /register //
router.post('/register', function(req, res, next) {
res.render('Welcome to Fit 7');
})
var username = req.body.username;
var email = req.body.email;
var password = req.body.password;
var newuser = new User();
newuser.username = username;
newuser.email = email;
newuser.password = password;
newuser.save(function(err, savedUser) {
if(err) {
console.log(err);
return res.status(500).send();
}
return res.status(200).send();
})
module.exports = router;
App JS Code:
// var createError = require('http-errors');
var express = require('express');
var app = express();
var path = require('path');
// var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var pug = require('pug');
// var indexRouter = require('./routes/index');
var workouts = require('./routes/workouts');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
// view engine setup
app.set('view engine', 'pug');
app.set('views', path.join(__dirname, 'views'));
// app.use(cookieParser());
// app.use(express.static(path.join(__dirname, 'public')));
// app.use('/', indexRouter);
// app.use('/api/workouts', workouts);
app.get('/', function (req, res) {
res.render('index')
})
//Registration Route for New Users
app.get('/register', function (req, res) {
res.render('register')
});
app.get('/home', function (req, res) {
res.render('home');
});
app.get('/workout/new', function (req, res) {
res.render('workoutform');
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
Pug Template Code:
body(data-gr-c-s-loaded='true', style='')
.container
form(action='/register', method='post').form-signin
h1.form-signin-heading Login to Fit-7
label.sr-only(for='username') Name
input#name.form-control(type='username', placeholder='username',
required='', autofocus='')
label.sr-only(for='email') Email address
input#inputEmail.form-control(type='email', placeholder='email address',
required='', autofocus='')
label.sr-only(for='password') Password
input#password.form-control(type='password', placeholder='password',
required='')
button.btn.btn-lg.btn-primary.btn-block(type='submit') Sign in
span._hsShareImage.hsShareImage  
loom-container#lo-engage-ext-container
loom-shadow(data-reactroot='', classname='resolved')
You dont seem to import the router anywhere in your app.js. First add
var registerRoute = require("./path/to/route.js");
after your other requires. Then add
app.use(registerRoute)
in place of this line:
app.get('/register', function (req, res) {
res.render('register')
});
I still dont have a reputation to like the comment above or comment, but the answer was very helpful.
But my problem was that I had the bellow line:
app.use('/', routes);
So I changed to where my application was
app.use('/Live/api', routes);
I'm using express with pug

Uploading an image to mongodb using Multer with Express and Axios

I am basically trying to make a small application which allows an admin user to enter a name, price and image of a product which can then be viewed on another page. The details will be sent to a mongo database which will be performed via an axios post from the front end. I can send the name and the price no problem which can be seen on the front end dynamically, however, I am unable to send image to the mongo database which i've been trying to achieve now for quite some time.
I am using multer and axios to try and sent the file over as the application is a react app. I think the problem is to do with the "req.file" within the back end of the application. The code below is my endpoint:
api.js
var express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors')
var app = express();
var mongodb = require('mongodb');
var path = require('path');
var fsextra = require('fs-extra');
var fs = require('fs')
var util = require('util')
var multer = require('multer')
var upload = multer( {dest: __dirname + '/uploads'} )
var ejs = require('ejs')
const MongoClient = require('mongodb').MongoClient;
app.use(express.static(path.resolve(__dirname, '../react', 'build')));
app.get('*',(req,res)=>{
res.sendFile(path.resolve(__dirname, '../react', 'build', 'index.html'));
});
console.log(__dirname)
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', __dirname);
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
var db;
mongodb.MongoClient.connect('mongodb://<mydbdetails>', (err, database) => {
if (err) {
console.log(err)
process.exit(1);
}
db = database;
console.log('Database connection is ready')
});
var server= app.listen(process.env.PORT || 8082, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
app.post('/api/submitImage', upload.single('inputForm'), function(req,res){
var file = req.body.file
if (file == null) {
// If Submit was accidentally clicked with no file selected...
//res.render('admin', { title:'Please select a picture file to submit!'});
res.send({success: false, message: "dsfdsg"})
console.log('There is no file present')
console.log(req.file,'file')
}
else{
// read the img file from tmp in-memory location
var newImg = fs.readFileSync(req.files.path);
console.log(newImg,'details of the new image')
// encode the file as a base64 string.
var encImg = newImg.toString('base64');
console.log(encImg,'kdfjndodj')
// define your new document
var newItem = {
description: req.body.description,
contentType: req.file.mimetype,
size: req.files.size,
img: Buffer(encImg, 'base64')
};
db.collection('products').insert(newItem, function(err, result){
if(err) {
console.log(err)
}
var newoid = new ObjectId(result.ops[0]._id);
fs.remove(req.file.path, function(err) {
if (err) { console.log(err) };
res.render('./src/components/adminContainer.js', {title:'Thanks for the Picture!'});
});
})
}
})
The next code is the how I am trying to send it over using Axios:
import axios from 'axios';
class ProductsApi {
static submitProduct(name,prices,callback){
axios.post('http://localhost:8082/api/submitProduct', {name: name, prices: prices})
.then( response => {
callback(response)
})
}
static viewName(callback){
axios.post('http://localhost:8082/api/retrieveName')
.then( response => {
return callback(response)
})
}
static viewPrice(callback){
axios.post('http://localhost:8082/api/retrievePrice')
.then( response => {
return callback(response)
})
}
static viewProducts(callback){
axios.post('http://localhost:8082/api/retrieveProducts')
.then( response => {
return callback(response)
})
}
static submitImages(image,callback){
axios.post('http://localhost:8082/api/submitImage',{image: image})
.then( response => {
return callback(response)
console.log('response has been made,', image,'has been recieved by axios')
})
}
}
export default ProductsApi;
The last file is how I am trying to send the file to the database using react with event handlers:
import React, { Component } from 'react'
import '../App.css'
import AppHeader from './appHeader.js'
import ProductsApi from '../api/axios.js'
const AdminContainer = () => {
return(
<div>
<AppHeader />
<FormContainer />
</div>
)
}
class FormContainer extends Component{
constructor(props){
super(props);
this.state={
file: '',
inputName: '',
inputPrice: '',
image: ''
};
this.handleNameChange = this.handleNameChange.bind(this);
this.handlePriceChange = this.handlePriceChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.sendName = this.handleSubmit.bind(this);
}
handleNameChange(e){
console.log(e.target.value)
this.setState({
name : e.target.value,
})
}
handlePriceChange(e){
console.log(e.target.value)
this.setState({
prices : e.target.value
})
}
sendName(e){
this.setState({
inputName: e.target.value,
inputName:e.target.value
})
}
handleSubmit(e){
e.preventDefault();
console.log('attempting to access axios...')
ProductsApi.submitProduct(this.state.name, this.state.prices, resp => {
console.log('response has been made', resp)
//if error message, add to state and show error message on front end
this.setState({
inputName:this.state.name,
inputPrice:this.state.prices
},function(){
console.log(resp,'this is resp')
console.log('Axios has send ',this.state.name,' to the database')
});
})
console.log(this.state.prices,'This is the new price')
console.log(this.state.name,'This is the new name')
ProductsApi.submitImages(this.state.image, response => {
console.log('axios has been notified to submit an image...')
this.setState({
image: this.state.image
},function(){
console.log('Image submission axios response details are as follows: ', response)
console.log(this.state.image, ': has been sent to the db')
})
})
}
render(){
return(
<div>
<h2>Add a new product to the Shop</h2>
<div className='formWrapper'>
<div className='center'>
<form name='inputForm' encType='multipart/form-data' method='post'>
<label>
Name:
<input value = {this.state.name} onChange={this.handleNameChange} type="text" placeholder='Name' /><br />
Price:
<input value = {this.state.prices} onChange={this.handlePriceChange} type='text' /><br />
</label>
<label>
Choose an Image:
<input className='imgInsert' name ='inputForm' type='file'/>
</label>
<div>
<img className = 'previewImage' value={this.state.image}/>
</div>
<button className='btn updateBtn' onClick={(e) => this.handleSubmit(e)}>Submit</button>
</form>
</div>
</div>
</div>
)
}
}
export default AdminContainer
Common errors I am getting when trying debug it is
TypeError: Cannot read property 'path' of undefined."
and "file" being undefined.
When using multer to save images you need to make sure that the image comes to the server as form data. this is because multer requires the multipart/form-data encoding which you do not get when submitting a form with an ajax request unless if you specifically do something to make it happen.
You can do this by using the FormData object. Here is an example of this being used. I hope this helps.

How to separate the routes and database functionality from appRouter.js using NodeJS and Express

in angularjs at express services I want all the calling services at one place.. something like this structure..
routes(some folder)|-API (all calls)|-Services|-schemas(mongoose)
if these are my services
'use strict';
var express = require('express');
var router = express.Router();
var conveyModel = require('../model/Schema');
console.log("convey api router ready");
/* GET /convey listing. */
router.get('/', function(req, res, next) {
console.log("convey api get '/'");
conveyModel.find(function (err, convey) {
if (err) return next(err);
res.json(convey);
});
});
/* POST /convey */
router.post('/', function(req, res, next) {
console.log("convey api post '/'");
console.log("retrieving:: " + req.body);
conveyModel.create(req.body, function (err, post) {
console.log("saving:: " + post);
if (err) return next(err);
res.json(post);
});
});
module.exports = router
i want to call all services in other Api js somthing like this,
router.post('/api/v1/login', auth.login);
router.get('/api/v1/me', users.getAll);
I'm not able to understand how it works... if there is some working example, with what I want it would be great.
silly me found answer long back but wanan update what i found!!!
in API.js all api calls i gathered like this
var express = require('express');
var router = express.Router();
var fact = require('../services/factRouter');
router.get('/fact', fact.getAll);
router.post('/fact/', fact.create);
module.exports = router;
and in services
'use strict';
var express = require('express');
var router = express.Router();
var factModel = require('../model/factSchema');
var users = {
getAll: function(req, res, next) {
console.log("fact api get '/'");
factModel.find(function (err, fact) {
if (err) return next(err);
res.json(fact);
});
},
create: function(req, res, next) {
console.log("fact api post '/'");
console.log("retrieving:: " + req.body);
factModel.create(req.body, function (err, post) {
console.log("saving:: " + post);
if (err) return next(err);
res.json(post);
});
}
};
module.exports = users;
and obviously in schema
'use strict';
var mongoose = require('mongoose');
var factsSchema = new mongoose.Schema({
title: { type: String },
description: { type: String },
});
module.exports = mongoose.model('facts', factsSchema);
console.log("facts schema defined")
yaaa dat was easy !!!
You can do something like this, in your routes.js can do this:
var express = require('express');
//by right app should have been created beforehand in index.js or app.js
//and just imported here
var app = express();
app.use('/api/users', require('./api/users');
...
then in /api/users create an index.js file with the following content:
var express = require('express');
var router = new express.Router();
var controller = require('./controller');
var auth = require('./service');
router.get('/', auth.isAuthenticated(), controller.getProfile);
module.exports = router;
Put your router controller in ./api/user/controller.js and logic (e.g. database layer or middleware) into ./api/user/service.js.
This is not the only architecture pattern you can use, but it must give you some ideas where to go from here

Why wont this post?

I'm playing around with mongodb + Express and rewriting an old comments app in the latest version of Express.
I've had to change a few things because of the changes in the latest Express. But I'm having some issues.
Basically, it won't post to /create when I submit my form. This is probably a simple fix but any help would be appreciated :)
app.js
require('./models/comments'); // require the model before the 'index.js' file is called
var express = require('express'); var path = require('path'); var favicon = require('static-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser');
var routes = require('./routes/index'); var create = require('./routes/create');
var app = express();
// Database stuff var mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/comments-app');
// view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade');
app.use(favicon()); 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('/create', create);
/// catch 404 and forward 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;
Comments.js (model)
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var CommentSchema = new Schema({
username: String,
content: String,
created: Date
});
module.exports = mongoose.model('Comment', CommentSchema);
index.jade
extends layout
block content
h1= title
div.addCommentForm
form( method="post", action="/create")
input(type='text', class='nameTxt', name='username')
div
span.label Comment :
textarea(name='comment')
div#addCommentSubmit
input(type='submit', value='Save')
br
br
#comments
- each comment in comments
div.comment
div.name comment.username
div.created_at= comment.created
br
div.content= comment.content
hr
create.js (route)
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Comment = mongoose.model('Comment', Comment);
router.route('/create')
.post(function(req, res) {
var Comment = new Comment()
username : req.body.username;
content : req.body.comment;
created : Date.now();
Comment.save(function(err) {
if (err)
res.send(err);
res.send('Comment added');
});
});
module.exports = router;
Your jade indenting for the form tag is off. Make sure the input tags you want inside the form tag in the HTML are indented further than the form tag in your jade so they end up as children of the form tag in the HTML.
Oops:
this jade
form
input
yields this HTML
<form></form><input>
Fixed
form
input
yields
<form><input></form>