EmberJS empty req body - node.js

I am new to EmberJS and I'm trying to save some data to Amazon DynamoDB using nodejs and expressjs as back-end but I'm getting a empty req body when submit my form through EmberJS.
If I try it using curl, as follows, I can save the data successfully, hence this shows that the back-end is working properly.
curl --header "Content-Type: application/json" --data '{"user":{"email":"teste#teste.com","firstName":"teste","lastName":"last name","password":"teste"}}' http://localhost:3000/api/users
I tried to set the Content-Type header in the application.js JSONAPIAdapter but got no luck. I also tried to use a REST adapter and got no luck also.
Following is my code:
Front-end
model - user.js
import DS from 'ember-data';
export default DS.Model.extend({
email: DS.attr('string'),
firstName: DS.attr('string'),
lastName: DS.attr('string'),
password: DS.attr('string'),
});
template - register.hbs
<div class="container" style="margin-top: 30px;">
<div class="row">
<form class="col s12" name="registerForm" id="registerForm">
<div class="row">
<div class="input-field col s6">
{{input name="firstName" name="firstName" type="text" value=model.firstName class="validate" required="required" aria-required="true"}}
<label for="firstName">First Name</label>
</div>
<div class="input-field col s6">
{{input name="lastName" name="lastName" type="text" value=model.lastName class="validate" required="required" aria-required="true"}}
<label for="lastName">Last Name</label>
</div>
</div>
<div class="row">
<div class="input-field col s6">
{{input type="email" value=model.email name="email" class="validated" }}
<label for="email">Email</label>
</div>
<div class="input-field col s6">
{{input name="password" name="password" type="password" value=model.password class="validate" required="required" aria-required="true"}}
<label for="password">Password</label>
</div>
</div>
</form>
</div>
<div class="row">
<div class="col s6 m6 l6">
<button class="waves-effect waves-light center-align btn col s6 m6 l6 teal darken-1" {{action 'register'}} >Register Me!</button>
</div>
<div class="col s6 m6 l6">
{{#link-to 'main'}}Cancel{{/link-to}}
</div>
</div>
</div>
route - register.js
import Ember from 'ember';
export default Ember.Route.extend({
model() {
return this.store.createRecord('user');
},
actions: {
willTransition() {
// rollbackAttributes() removes the record from the store
// if the model 'isNew'
this.controller.get('model').rollbackAttributes();
},
register() {
let email = this.controller.get('model.email');
let firstName = this.controller.get('model.firstName');
let lastName = this.controller.get('model.lastName');
let password = this.controller.get('model.password');
let user = {
email: email,
firstName: firstName,
lastName: lastName,
password: password
};
console.log('USER === ' + JSON.stringify(user));
const newUser = this.store.createRecord('user', {
user
});
newUser.save().then((response) => {
alert('Registro efetuado com sucesso ! ID = ' + response.get('id'));
this.set('email', '');
this.set('firstName', '');
this.set('lastName','');
this.set('password','');
this.transitionTo('main');
});
},
}
});
Back-end - NodeJS + ExpressJS
app.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
console.log('ENV = ' + process.env.NODE_ENV);
var cors;
if (process.env.NODE_ENV == 'production') {
cors = 'https://www.myserserver.com';
}
else {
cors = 'http://localhost:4200';
}
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', cors);
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
next();
});
var globSync = require('glob').sync;
var routes = globSync('./routes/*.js', { cwd: __dirname}).map(require);
var ddb = require('dynamodb').ddb(
{
accessKeyId: 'XXXXX',
secretAccessKey: 'ZZZZZZZ',
endpoint: 'dynamodb.eu-west-1.amazonaws.com'
});
routes.forEach( function(route) {
route(app, ddb);
});
module.exports = app;
route - users.js
var express = require('express');
var uuid = require('node-uuid');
var crypto = require('crypto');
module.exports = function(app, client) {
var router = express.Router();
var options = { attributesToGet: ['nome'],
consistentRead: true
};
router.get('/users',function(req, res, next){
client.scan('users', {}, function(err, data) {
if(err) {
return res.status(200).json({"erro": err});
}
else {
res.send({user:data.items});
}
});
});
router.post('/users',function(req, res, next) {
var payload = req.body.user;
console.log('\n REQ BODY = ' + JSON.stringify(req.body) + '\n\n');
var response = '';
var id = uuid.v1();
var salt = crypto.randomBytes(16).toString('hex');
var password = payload.password; //req.body.password;
var hash = crypto.pbkdf2Sync(password, salt, 1000, 64,'sha512').toString('hex');
var firstName = payload.firstName;
var lastName = payload.lastName;
var email = payload.email;
var user = {
id: id,
email: email,
firstName: firstName,
lastName: lastName,
hash: hash,
salt: salt
}
console.log(user);
client.putItem('users', user, {}, function(err, res, cap) {
if (err) {
this.response = ('erro = ' + err);
}
else {
//console.log('PutItem: ' + cap);
console.log(res);
//this.response = ('User registered!');
}
});
return res.status(200);
});
app.use('/api', router);
};
This is the console.log for req.body when I send the data using EmberJS:
REQ BODY = {"user":{"email":null,"firstName":null,"lastName":null,"password":null}}
What am I missing here?
Thanks very much for the help!

Got it running.
For those facing the same problem, I just replace my register action with this one:
register: function() {
var _this = this;
this.get('model').save()
.then(function(data) {
console.log('signup response:', data);
alert('signup saved ok! redirect to signin');
_this.transitionToRoute('main');
},
function(data) {
alert('signup saved fail!');
_this.set('error', data.responseJSON.error || 'sorry, signup failed.');
});
}

Related

how to solve this Cannot POST error in MERN?

I am inserting two images along with the form data into MongoDB database.
While both images are stored in my pc folder but all form data isn't uploading in the database.
error
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot POST /</pre>
</body>
</html>
in my console. Please help me how to solve that.
I have tried some previously asked question in stackOF.
app.js
const express = require("express")
const app = express()
const cors = require('cors');
const env = require("dotenv")
const port = 5000
env.config({path: "../server/config.env"})
require("../server/db/conn")
app.use(cors());
app.use(express.json())
app.use(require("../server/router/auth"))
app.listen(port, (err) => {
if (err) {
return console.error(err);
}
return console.log(`server is listening on ${port}`);
});
module.exports = "conn"
register.js(frontend)
const Register = () => {
const [newUser, setNewUser] = useState({
school: "",
address: "",
photo: "",
photoone: ""
});
const handleSubmit = (e) => {
e.preventDefault();
const formData = new FormData();
formData.append("school", newUser.school);
formData.append("photo", newUser.photo);
formData.append("photoone", newUser.photoone)
formData.append("address", newUser.address);
axios({
method: "post",
url: "/teacher",
data: formData,
headers: { "Content-Type": "multipart/form-data" },
})
.then((response) => {
console.log(response)
}).then((data) => {
console.log(data)
}).catch((error) => {
if (error.response) {
console.log(error.response.data)
}
})
};
const handleChange = (e) => {
setNewUser({ ...newUser, [e.target.name]: e.target.value });
};
const handlePhoto = (e) => {
setNewUser({ ...newUser, photo: e.target.files[0] });
};
const handlePhotoone = (e) => {
setNewUser({ ...newUser, photoone: e.target.files[0] });
};
return (
<>
<div className="container main">
<div className="row">
<div className="col-sm-6 col-md-6 col-lg-6">
<form onSubmit={handleSubmit} encType="multipart/form-data">
<div class="mb-3">
<label class="form-label">
Your school
</label>
<input
type="text"
class="form-control"
id="exampleInputPassword1"
id="school"
name="school"
value={newUser.school}
onChange={handleChange}
/>
</div>
<div class="input-group mb-3">
<input
type="file"
id="pic"
accept=".png, .jpg, .jpeg"
name="photo"
onChange={handlePhoto} type="file" class="form-control" id="inputGroupFile02" />
</div>
<div class="input-group mb-3">
<input
type="file"
id="pic"
placeholder="second photo"
accept=".png, .jpg, .jpeg"
name="photoone"
onChange={handlePhotoone} type="file" class="form-control" id="inputGroupFile01" />
</div>
<div class="mb-3">
<label for="exampleInputEmail1" class="form-label">
your address
</label>
<input
type="text"
id="address"
name="address"
value={newUser.address}
onChange={handleChange}
class="form-control"
aria-describedby="emailHelp"
/>
</div>
<button
value="register"
type="submit"
class="btn btn-primary"
>
Submit
</button>
</form>
</div>
</div>
</div>
</>
);
};
auth.js(backend)
const mongoose = require("mongoose")
const express = require("express")
const router = express()
require("../db/conn")
const User = require("../model/userSchema")
const Teacher = require("../model/userSchemaTeacher")
const multer = require('multer');
let path = require('path');
let fs = require("fs-extra");
const storage = multer.diskStorage({
destination: function (req, file, cb) {
let schoolname = req.body.school;
let path = `C:/Users/kumar/Desktop/mern/server/images/${schoolname}`;
fs.mkdirsSync(path);
cb(null, path);
// cb(null, 'images');
},
filename: function (req, file, cb) {
cb(null, file.originalname);
}
});
const fileFilter = (req, file, cb) => {
const allowedFileTypes = ['image/jpeg', 'image/jpg', 'image/png'];
if (allowedFileTypes.includes(file.mimetype)) {
cb(null, true);
} else {
cb(null, false);
}
}
let upload = multer({ storage, fileFilter });
router.route('/teacher').post(upload.fields([{
name: "photo", maxCount: 1
}, {
name: "photoone", maxCount: 1
}
])), (req, res) => {
const school = req.body.school;
const photo = req.file.filename
const photoone = req.file.filename
const address = req.body.address;
const newUserData = {
school,
photo,
photoone,
address,
}
const newUser = new Teacher(newUserData);
newUser.save()
.then(() => res.json('User Added'))
.catch((err) => {
console.log(err);
});
}
Please see how to solve that?
The route you are trying to POST your form data is not defined please set your route path like this:
router.post('/teacher',upload.fields([{
name: "photo", maxCount: 1
}, {
name: "photoone", maxCount: 1
}
]), (req, res) => {
const school = req.body.school;
const photo = req.files['photo'][0]
const photoone = req.files['photoone'][0]
const address = req.body.address;
const newUserData = {
school,
photo,
photoone,
address,
}
const newUser = new Teacher(newUserData);
newUser.save()
.then(() => res.json('User Added'))
.catch((err) => {
console.log(err);
});
})
...

req.file is undefined in multer image upload -- NodeJS, Angular

I am trying to upload an image for a blog posts using Multer. I am using mongodb and NodeJS for the backend and Angular for the front end. Whenever I perform the POST request and check in the console, the req.file is always undefined. I have tried using Multer's upload.any() with req.files and req.files[0].filename but to no avail. I have no clue why it stays undefined.
Here's my Multer Code:
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, 'public');
},
filename: (req, file, cb) => {
console.log(file);
var filetype = '';
if(file.mimetype === 'image/gif') {
filetype = 'gif';
}
if(file.mimetype === 'image/png') {
filetype = 'png';
}
if(file.mimetype === 'image/jpeg') {
filetype = 'jpg';
}
cb(null, 'file-' + Date.now() + '.' + filetype);
}
});
const upload = multer({storage: storage, limits: { fieldSize: 10 * 1024 * 1024 } });
Here's the Server POST request:
router.post('/newPost', passport.authenticate('jwt', { session: false}), upload.single('image'), function(req, res, next) {
console.log(req.file);
let newPost = new Post({
postTitle: req.body.postTitle,
postAuthor: req.body.postAuthor,
postImgUrl: 'http://localhost:3000/public/' + req.file.filename,
postContent: req.body.postContent
});
Post.create(newPost, (err, user) => {
if(err) {
res.json({success: false, msg: 'Post failed to submit'});
} else {
res.json({success: true, msg: 'Successfully Posted'});
}
});
});
This is my Angular Service for the POST request:
addPost(post): Observable<post> {
this.loadToken();
const head = this.headers.append("Authorization", this.authToken);
return this.http.post<post>(this.baseUri + "/newPost", post, { headers: head });
}
This is my TypeScript Component code:
export class BlogAddComponent implements OnInit {
postTitle: '';
postAuthor: '';
postContent: '';
postImgUrl: string;
post: any[] = [];
postForm: FormGroup;
public editor = Editor;
config;
constructor(private postService: PostService,
private formBuilder: FormBuilder,
private router: Router,
private flashMessage: FlashMessagesService) {
}
onFileSelect(event: Event) {
const file = (event.target as HTMLInputElement).files[0];
this.postForm.patchValue({ image: file });
const allowedMimeTypes = ["image/png", "image/jpeg", "image/jpg"];
if (file && allowedMimeTypes.includes(file.type)) {
const reader = new FileReader();
reader.onload = () => {
this.postImgUrl = reader.result as string;
};
reader.readAsDataURL(file);
}
}
ngOnInit(): void {
this.postForm = new FormGroup({
postTitle: new FormControl(null),
postAuthor: new FormControl(null),
postContent: new FormControl(null),
postImgUrl: new FormControl(null)
});
}
onBlogSubmit() {
this.postService.addPost(this.postForm.value).subscribe(
data => {
this.flashMessage.show('Blog Submitted Successfully', {cssClass: 'alert-success', timeout: 3000});
this.router.navigate(['/blog-page']);
},
error => {
this.flashMessage.show('Something Went Wrong', {cssClass: 'alert-danger', timeout: 3000});
}
);
}
}
And this is my Component HTML:
<body>
<div [formGroup]="postForm" class="container" *ngIf="post">
<h1 class="mb-4">New blog post</h1>
<form [formGroup]="postForm" (ngsubmit)="onBlogSubmit()" enctype="multipart/form-data">
<div class="form-group">
<label for="postImgUrl">Image</label>
<input (change)="onFileSelect($event)" type="file" class="form-control" name="image" required>
</div>
<div class="form-group">
<label for="title">Title</label>
<input formControlName="postTitle" type="text" class="form-control" placeholder="Title" name="postTitle" required>
</div>
<div class="form-group">
<label for="author">Author</label>
<input formControlName="postAuthor" type="text" class="form-control" placeholder="Author" name="postAuthor" required>
</div>
<br>
<div class="form-group">
<ckeditor formControlName="postContent" name="postContent" [editor]="editor" [config]="config"></ckeditor>
</div>
<br>
<div class="form-group">
<a routerLink="/blog-page" class="btn btn-warning">Cancel</a>
<button type="submit" class="btn btn-primary" (click)="onBlogSubmit()">Save</button>
</div>
</form>
</div>
</body>
I am really stuck with this. Any help, pointers or guidance are greatly appreiciated. Thank You very much.
You should send formData with the name image as you configured on backend:
addPost(post): Observable<post> {
this.loadToken();
const head = this.headers.append("Authorization", this.authToken);
const formData: FormData = new FormData();
formData.append('image', post.postImgUrl);
return this.http.post<post>(this.baseUri + "/newPost", formData, { headers: head });
}

How to get MongoDB data to select option using NodeJS

I am trying to populate MongoDB data to html select option.
This is what I have done so far
I have created a database books and created collection AuthorDB
I manually inserted data (to check if it really is working)
But when I used postman to get data, I get an empty array means no data. (But I have inserted data to AuthorDB collection)
Here is my server.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const BookDB = require('./book-dbmodel');
const AuthorDB = require('./author-dbmodel');
const app = express();
const router = express.Router();
app.use(bodyParser.json());
app.use(cors());
app.use('/books', router);
//connect to books database
mongoose.connect('mongodb://127.0.0.1:27017/books', {useNewUrlParser: true});
const connection = mongoose.connection;
connection.once('open', () => {
console.log("Connected to MongoDB via port 27017");
});
app.listen(4000, () => {
console.log('Listening to port 4000');
});
// add book http://localhost:4000/books/add
router.route('/add').post((req, res) => {
let bookDB = new BookDB(req.body);
bookDB.save().then((bookDB) => {
res.status(200).send(`${bookDB} Added!`);
}).catch((err) => {
res.status(400).send({message: err});
});
});
//get all authors http://localhost:4000/books/authors
router.route('/authors').get((req, res) => {
AuthorDB.find((err, authors) => {
if(err) throw err;
res.status(200).send(authors);
});
});
//get books by author name http://localhost:4000/books/authors/authorName
router.route('/authors/authorName').get((req, res) => {
let authorName = req.params.authorName;
BookDB.find({firstName: {$regex: `${authorName}`, $options: "i"}}, (err, books) => {
if(err) throw err;
res.status(200).send(books);
});
});
And this is my App.js in front-end:
import React, {Component} from 'react';
import axios from 'axios';
const ShowAuthors = (props) => (
<option value={props.author.firstName}>{props.author.firstName}</option>
);
export default class AddBooks extends Component{
constructor(props){
super(props);
this.state = {
authorArray: [],
name: '',
isbn: 0,
author: '',
price: 0,
yearOfPublication: 0,
publisher: ''
}
}
//to get author list on dropdown select
componentDidMount(){
axios.get('http://localhost:4000/books/authors/')
.then(authors => {
console.log(authors.data);
this.setState({
authorArray: authors.data
});
}).catch(err => {
console.log(err);
});
}
getAuthors(){
return this.state.authorArray.map((currentAuthor, id) => {
return <ShowAuthors author={currentAuthor} key={id} />
});
}
onSubmit(){
}
onChangeName(){
}
onChangeISBN(){
}
render(){
return(
<div className="container">
<h1>Add Books</h1>
<form onSubmit={this.onSubmit}>
<div className="form-group">
<label htmlFor="book-name">Book Name</label>
<input
value={this.state.name}
onChange={this.onChangeName}
type="text" className="form-control" id="book-name" aria-describedby="emailHelp" placeholder="Book Name"/>
</div>
<div className="form-group">
<label htmlFor="book-isbn">ISBN</label>
<input
value={this.state.isbn}
onChange={this.onChangeISBN}
type="number" className="form-control" id="book-isbn" aria-describedby="emailHelp" placeholder="ISBN"/>
</div>
<div className="form-group">
<label htmlFor="author-name">Authors</label>
<select
className="form-control" name="authors" id="authors">
{this.getAuthors()} {/* this doesn't return anything but an empty array */}
</select>
</div>
<div className="form-group">
<label htmlFor="book-price">Book Price</label>
<input type="number" className="form-control" id="book-price" name="book-price" aria-describedby="emailHelp" placeholder="Book Price"/>
</div>
<div className="form-group">
<label htmlFor="book-year">Published Year</label>
<input type="number" className="form-control" id="book-year" name="book-year" aria-describedby="emailHelp" placeholder="Year"/>
</div>
<div className="form-group">
<label htmlFor="book-publisher">Book Publisher</label>
<input type="number" className="form-control" id="book-publisher" name="book-publisher" aria-describedby="emailHelp" placeholder="Publisher"/>
</div>
</form>
</div>
);
}
}
And this is my mongodb visualization:
And this is my AuthorDB schema model:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let AuthorDB = new Schema({
firstName: {type: String},
lastName: {type: String},
nationality: {type: String}
});
module.exports = mongoose.model('AuthorDB', AuthorDB);
for mongoose.model() method
The first argument is the singular name of the collection your model
is for. Mongoose automatically looks for the plural, lowercased
version of your model name. Thus, for the example above, the model
Tank is for the tanks collection in the database.
Mongoose trying to be smart and detect the model name, but you can force it to use the collection you want like this:
new Schema({..}, { collection: 'AuthorDB' })
Or when you create the model, like this:
module.exports = mongoose.model('AuthorDB', AuthorDB, 'AuthorDB')
Also you're trying to access this parameter req.params.authorName while it not defined in your route, you're missing : in your route.
router.route('/authors/authorName')
It should be like this:
router.route('/authors/:authorName')
to be able to get the authorName value.

Multer is uploading my image locally but not in my database

I Want to upload a image on my blog post and there is an error, image is alredy in the folder but when i see the database there is noimage.png set as default ...
Im using Multer , there is my code :
Addpost.ejs
<% include ./partials/header %>
<form method="POST" action="/posts/add" enctype="multipart/form-data">
<div class="form-group">
<label>Title</label>
<input class="form-control" name="title" type="text">
</div>
<div class="form-group">
<label>Category</label>
<select class="form-control" name="category">
<% categories.forEach(function(category){ %>
<option value="<%= category.title %>"><%= category.title %></option>
<% }) %>
</select>
</div>
<div class="form-group">
<label>Body</label>
<textarea class="form-control" name="body"></textarea>
</div>
<div class="form-group">
<label>Main Image</label>
<input class="form-control" name="file" type="file">
</div>
<div class="form-group">
<label>Author</label>
<select class="form-control" name="author">
<option value="Arsen Cenko">Arsen Cenko</option>
<option value="John Doe">John Doe</option>
</select>
</div>
<input class="btn btn-default" name
="submit" type="submit" value="save">
</form>
<script src="/app.js"></script>
PostSchema :
var mongoose = require("mongoose")
var postSchema = new mongoose.Schema({
title: String,
created: {type: Date, default: Date.now},
category: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Category"
}
],
body: String,
file: String })
module.exports = mongoose.model("Post", postSchema);
Post.js Route
var express = require("express");
var router = express.Router();
var Post = require("../models/post");
var Category = require("../models/category");
var path = require('path');
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './public/images/uploads/')
},
filename: function (req, file, cb) {
cb(null, Date.now() + path.extname(file.originalname))
} });
var upload = multer({ storage: storage });
router.get("/add", function(req, res) {
Category.find({}, function(err, categories){
if(err){
console.log(err);
} else{
res.render("addpost", {
title: "Add Post",
categories: categories
})
}
})
})
router.post("/add", upload.single('image'), function(req, res){
var title = req.body.title;
var category = req.body.category;
var body = req.body.body;
var author = req.body.author;
if(req.files && req.files.image){
var imageOriginalName = req.files.image.originalname;
var imageName = req.files.image.fieldname;
var imageMime = req.files.image.mimetype;
var imagePath = req.files.image.path;
var imageExt = req.files.image.extension;
var imageSize = req.files.image.size;
} else {
var imageName = "noimage.png";
}
var newPost = {title:title, category:category, body:body, author:author, image:imageName};
Post.create(newPost, function(err, newPost){
if(err){
console.log("Error");
} else{
res.redirect("/");
}
})
})
Thanks :)
Hey according to documentation
https://github.com/expressjs/multer
using upload.single('image') will get your file in "req.file" not in "req.files"
I think this is the reason your if case fails and jumps to else case. You cannot access it like req.file.image.filename you can simply access it via req.file.filename. Since it is already a "single" file. try console logging the req.file to know what you are getting.
update I think mistake is in your html
<input class="form-control" name="file" type="file">
should be
<input class="form-control" name="image" type="file">
the name attribute of the html should be same as the string in upload.single.
So in your case
upload.single('image')
Now you will receive file in req.file.
Hope it helps.

Angular2 - How to upload file with form data submit [(ngModel)] and save reference in MongoDB

I have this task page and want to upload a file with the form submit to the NodeJs express server.
#Component({
selector: 'tasks',
template: `<div mdl class="mdl-grid demo-content">
<div class="demo-graphs mdl-shadow--2dp mdl-color--white mdl-cell mdl-cell--8-col">
<h3>Create Task Page</h3>
<form action="#" (ngSubmit)="onSubmit()">
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<input class="mdl-textfield__input" type="text" id="taskname" [(ngModel)]="data.taskname"/>
<label class="mdl-textfield__label" for="taskname">Task Name</label>
</div> <br/>
<div class="mdl-textfield mdl-js-textfield">
<textarea class="mdl-textfield__input" type="text" rows= "5" id="taskdesc" [(ngModel)]="data.taskdesc"></textarea>
<label class="mdl-textfield__label" for="taskdesc">Task Description</label>
</div> <br/>
<select [(ngModel)]="data.assignedto">
<option *ngFor="#assign of dropdownValues" [ngValue]="assign.userEmail">{{assign.userEmail}}</option>
</select>
<div> <input type="file" placeholder="Upload file..."></div> <--How to handle this ?
<br/><br/> <button class="mdl-button mdl-js-button mdl-button--raised mdl-button--colored" type="submit">Create Task</button>
</form>
</div>
`,
directives: [ROUTER_DIRECTIVES, MDL]
})
export class CreateTaskComponent implements OnInit {
data: any;
onSubmit(form) {
console.log(JSON.stringify(this.data));
this.apartmentService.postTasks(this.data).then(_=>this.router.navigate(['Tasks']));
this.data = {};
}
}
The data is posted to the expressjs server as follows
Server.ts
router.route('/api/newtask')
.post(function(req, res) {
var task = new Task();
task.taskname = req.body.taskname;
task.taskdesc = req.body.taskdesc;
task.assignedto = req.body.assignedto;
task.taskstatus = 'OPEN';
task.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Task created!' });
});
})
The mongoose mondel for the mongodb is as follows.
Mongoose Model
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var TaskSchema = new Schema({
taskname: String,
taskdesc: String,
taskcreator:String,
createddate: String,
assignedto: String,
taskstatus: String
});
module.exports = mongoose.model('Task', TaskSchema);
How can I upload a file and associate it with the current data on the form ?
plz see this article https://www.npmjs.com/package/multer
you can use multer in server side and very easy :
var express = require('express')
var multer = require('multer')
var upload = multer({ dest: 'uploads/' })
var app = express()
app.post('/profile', upload.single('avatar'), function (req, res, next) {
// req.file is the `avatar` file
// req.body will hold the text fields, if there were any
})
app.post('/photos/upload', upload.array('photos', 12), function (req, res, next) {
// req.files is array of `photos` files
// req.body will contain the text fields, if there were any
})
var cpUpload = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }])
app.post('/cool-profile', cpUpload, function (req, res, next) {
// req.files is an object (String -> Array) where fieldname is the key, and the value is array of files
//
// e.g.
// req.files['avatar'][0] -> File
// req.files['gallery'] -> Array
//
// req.body will contain the text fields, if there were any
})

Resources