how to friend invite send to mail? - html

(Update)Hi all i want to invite friend sent to mail using Nodejs. Mainly server side user and pass which can be use? and mail also can't sent then i tried many ways but unable to get the solution if any one knows the solution please help me.....
myplunker
HTML:-
<div id="container">
<center>
<input id="to" type="text" placeholder="Enter E-mail ID" /><br><br>
<input id="subject" type="text" placeholder="Write Subject" /><br><br>
<textarea id="content" cols="40" rows="5" placeholder="Message"></textarea><br><br>
<button id="send_email">Send Email</button>
</center>
<span id="message"></span>
</div>
Server:-
var smtpTransport = nodemailer.createTransport("SMTP",{
service: "Gmail",
use_authentication: true,
auth: {
user: "sample#gmail.com",
pass: "password"
}
});
app.get('/',function(req,res){
res.sendfile('index.html');
});
app.get('/send',function(req,res){
var mailOptions={
to : req.query.to,
subject : req.query.subject,
text : req.query.text
}
console.log(mailOptions);
smtpTransport.sendMail(mailOptions, function(error, response){
if(error){
console.log(error);
res.end("error");
}else{
console.log("Message sent: " + response.message);
res.end("sent");
}
});
});

The Following steps may help you:
Add var nodemailer=require("nodemailer") to the top of your server
script
Add var express=require("express"); var app=express() to the top of your server script
To Test that the email is being sent move what is in your app.get("/send") script outside the function and comment everything else (For Now) should Look similar to this:
var nodemailer=require("nodemailer");
var express=requre("express");
var app=express();
var smtpTransport = nodemailer.createTransport("SMTP",{
service: "Gmail",
use_authentication: true,
auth: {
user: "email#domain.com",
pass: "PASS"
}
});
var mailOptions={
to : "email#domain.com",
subject :"SUBJECT",
text : "MESSAGE"
}
console.log(mailOptions);
smtpTransport.sendMail(mailOptions, function(error, response){
if(error){
console.log(error);
}else{
console.log("Message sent: " + response.message);
}
});
/*
app.get('/',function(req,res){
res.sendfile('index.html');
});
app.get('/send',function(req,res){
var mailOptions={
to : req.query.to,
subject : req.query.subject,
text : req.query.text
}
console.log(mailOptions);
smtpTransport.sendMail(mailOptions, function(error, response){
if(error){
console.log(error);
res.end("error");
}else{
console.log("Message sent: " + response.message);
res.end("sent");
}
});
});*/
Make sure you have this turned on for the email you are trying to send an email with: https://www.google.com/settings/security/lesssecureapps
Make Sure your version of nodemailer is correct, It should be 0.71v for the setup you have: How to downgrade this node.js module to specific version and prevent automatic upgrade later?
Run the server script with a terminal: node fileName.js (If none of the tips help could you please copy the error stack?)
If everything works uncomment everything and delete the mailOptions and smtpTransport that are outside the app.get. Everything should work now...
Good Luck, And I'll be happy to help if you have any more problems.

Related

creating DELETE request using nodejs on sql database

New to node.js and learning how to use mysql with node. I have a form.html that has two buttons to input a department_no and a department_name. I am succecfully able to insert into mysql database but I have no clue on how to delete a specific dept_no. What I want to be able to do is enter a dept_no and the dept_name and then DELETE from my database based on the dept_no. Also I want to be able to check what the user enters to make sure that it is a valid dept_no and dept_name. Any ideas on how to get started or what to look into to be able to do this would be extremely helpful. I will paste my node.js and form.html down below.
node.js
// DELETE BELOW
app.delete("/deleteEmp/", (req, res) => {
console.log("Department number is " + req.body.department_no);
console.log("Department name is " + req.body.department_name);
const deptNumber = req.body.department_no;
const deptName = req.body.department_name;
const connection = mysql.createConnection({
host: "localhost",
user: "root",
database: "employees"
});
const queryString = "DELETE departments WHERE dept_no = ?";
connection.query(queryString, [department_no], (err, results, fields) => {
if (err) {
console.log("Could not delete" + err);
res.sendStatus(500);
return;
}
console.log("Deleted department_no with dept_name");
res.end();
});
});
form.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>SQLFORM</title>
<style>
#space {
margin-top: 20px;
}
</style>
</head>
<body>
<div>Fill Form Below</div>
<hr />
<div id="space">
<form action="/deleteEmp" method="DELETE">
<input placeholder="Enter Department Number" name="department_no" />
<input placeholder="Enter Department Name" name="department_name" />
<button>Submit</button>
</form>
</div>
</body>
</html>
HTML forms do not support DELETE requests in general. Node apps can use a work-around like this one - https://github.com/expressjs/method-override
Another alternative is to perform an AJAX request that doesn't have restrictions on allowed methods. A simplified example:
document.querySelector('#space form').addEventListener('submit', (event) => {
event.preventDefault();
let formData = new FormData();
formData.append('department_no', document.querySelector("input[name='department_no']").value);
formData.append('department_name', document.querySelector("input[name='department_name']").value);
fetch('https://yoururl.com/deleteEmp', {
method: 'DELETE',
headers: {
"Content-type": "application/x-form-urlencoded"
},
body: formData
});
});

error in uploading the image from angular to nodejs

My Html file is -
<form method="post" [formGroup]="orderForm" enctype="multipart/form-data" (ngSubmit)="OnSubmit(orderForm.value)" >
<div class="form-group">
<label for="image">Select Branch Image</label>
<input type="file" formControlName="branchImg" (change)="onFileChange($event)" class="form-control-file" id="image">
</div>
</form>
and my .ts file is -
public orderForm: FormGroup;
onFileChange(event) {
const reader = new FileReader();
if (event.target.files && event.target.files.length) {
const [file] = event.target.files;
reader.readAsDataURL(file);
reader.onload = () => {
this.orderForm.patchValue({
branchImg: reader.result
});
};
}
}
ngOnInit() {
this.orderForm = this.formBuilder.group({
branchImg: [null, Validators.required]
});
}
and then submit the form.
I am supposed to get the image address and the upload that address in cloudinary
But when I am consoling the body in my nodejs app
it gives something like this-
branchImg: 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAgAAAQABAAD/7QCEUGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAGccAigAYkZCTUQwMTAwMGE4MjBkMDAwMD and so on.
I don't think that it is the images address. Can anyone tell me that what is this? and how to get that image's address which I will upload to cloudinary
As the Eric suggest -
my app.js code is
router.post('/branch',(req,res) =>{
const body = req.body;
const base64Data = body.branchImg.replace(/^data:image\/png;base64,/, "");
console.log(base64Data);
fs.writeFile("out.jpg", base64Data, 'base64', function(err,result) {
console.log(result);
});
});
it gives result as undefined
That basically is a base64 encoding of the image data. What you need to do after you get that is write that to a file, and then upload it to cloudinary
//this will write the base64 data as a jpg file to your local disk
require("fs").writeFile("out.jpg", base64Data, 'base64', function(err) {
//after you write it to disk, use the callback space here to upload said file
//to your cloudinary endpoint
});

How can i upload audio file to Cloudinary with Node.js?

i deeply need help with this audio file upload to cloudinary issue I have had for several days now. I tried many times to make it work, but i am still struggling. I am a beginner backend developer, so please any help is appreciated.
It is an mp3 player App. When i upload a song, the title gets saved in DB, but the Audio isn't. This is the MP3 PLAYER page screenshot. It shows the title being saved and rendered from DB but not the audio file.
Audio upload form
<form class="ui form" action="/albums/<%= album._id %>/songs" method="POST" enctype="multipart/form-data">
<div class="field">
<label>Song Title:</label>
<input type="text" id="title" name="song[title]" placeholder="song title...." required>
</div>
<div class="field">
<label>Song file:</label>
<input type="file" id="song" name="audio" accept="audio/*" required>
</div>
<div class="field">
<input class="fluid ui green button" type="submit" id="submit" value="Enter">
</div>
Exit
</form>
Song model
var mongoose = require("mongoose");
//Album Schema
var audioSchema = new mongoose.Schema({
title: String,
audio: String,
date: {type: Date, default: Date.now()}
});
//exporting the Schema
module.exports = mongoose.model("Audio", audioSchema);
Backend code/ROUTE
var express = require("express"),
router = express.Router({mergeParams: true}),
middleware = require("../middleware"),
Album = require("../models/album"),
Song = require("../models/songs"),
multer = require("multer")
var storage = multer.diskStorage({
filename: function(req, file, callback) {
callback(null, Date.now() + file.originalname);
}
});
//uploader
var upload = multer({ storage: storage});
var cloudinary = require('cloudinary');
cloudinary.config({
cloud_name: 'proccess.env.CLOUDINARY_NAME',
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: process.env.CLOUDINARY_API_SECRET
});
//Songs new Route
router.get("/albums/:id/songs/new", middleware.isLoggedIn, function(req, res) {
//find Album by id
Album.findById(req.params.id, function(err, album) {
if(err) {
console.log(err);
} else {
res.render("songs/new", {album: album});
}
});
});
//Song POST route
router.post("/albums/:id/songs", middleware.isLoggedIn, upload.single("audio"), function(req, res) {
cloudinary.uploader.upload(req.file.path, function(result) {
// add cloudinary url for the mp3 to the album object under audio property
req.body.song.audio = result.secure_url;
//find Album by ID
Album.findById(req.params.id, function(err, album) {
if(err) {
console.log(err);
res.redirect("/albums/" + req.params.id);
} else {
//Creating Album and saving it to DB
Song.create(req.body.song, function(err, song) {
if(err) {
console.log("Opps something went wrong!" + err);
res.redirect("back");
} else {
//save the song to DB
song.save();
//this saves the songs object inside
album.songs.push(song);
//save album
album.save();
res.redirect("/albums/" + album._id);
}
});
}
});
});
});
module.exports = router;
cloudinary.uploader.upload(req.file.path, resource_type: "video", function(result)
That's because you will need to use GridFS from MongoDB to store data from a file.
https://docs.mongodb.com/manual/core/gridfs/#use-gridfs
As you are using Mongoose, please check this module : https://www.npmjs.com/package/mongoose-gridfs
The mongoose-gridfs module wrap the gridfs-stream module, and seems to fit to binary data upload. If you want, you can still do it yourself, by following this tutorial : http://niralar.com/mongodb-gridfs-using-mongoose-on-nodejs/

Editing Profile from HTML to MongoDB via Express / Node JS

I'm trying to build a web platform that where you can register and adapt your profile. However, I'm struggling with the editing part. Registration and Login are fine, but the rest gives an HTTP 500.
So here's what I did:
User Scheme for Mongoose:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var passportLocalMongoose = require('passport-local-mongoose');
//enhanced userSchema
var UserSchema = new Schema({
user_id: Schema.ObjectId,
username: {type :String, required : true, unique : true}, //serves as unique identifier
password: {type : String, required: true},
name: {type : String, required : true},
surname: String,
created_at : Date,
updated_at : Date,
skills: [{type : String}],
lectures: [{type : String}],
groups: [{type : String}] //todo: Change for later cross referencing with group schemes
});
UserSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model('User', UserSchema);
Followed by the Routing:
var express = require('express');
var router = express.Router();
var auth = require("../controllers/AuthController.js");
var profile = require ("../controllers/ProfileController");
// restrict index for logged in user only
router.get('/', auth.home);
// route to register page
router.get('/register.html', auth.register);
// route for register action
router.post('/register.html', auth.doRegister);
// route to login page
router.get('/login.html', auth.login);
// route for login action
router.post('/login.html', auth.doLogin);
// route for logout action
router.get('/logout.html', auth.logout);
//route to profile
router.get('/profile.html', profile.goToProfile);
//route for changing profile
router.post('/profile.html', profile.changeProfile);
module.exports = router;
And the profileController
/**
* Controller for editing the profile
*/
var mongoose = require("mongoose");
var passport = require("passport");
var User = require("../models/User");
var path = require('path');
//Change Name
var profileController = {};
//go to Profile
profileController.goToProfile = function (req, res){
res.sendFile(path.resolve('login.html')), {user : req.user};
}
profileController.changeProfile= function (req, res){
console.log("REQUEST: " + req.body.toString());
if (req.body.surname.isEmpty()){
}
else {
User.findByIdAndUpdate(req.user._id, { $set: { surname: req.body.surname }}, { new: true }, function (err, User) {
if (err) {
console.log(err.toString());}
res.alert('Changed surname');
console.log('changed surname')
});
};
if (req.body.name.isEmpty()){}
else {
User.findByIdAndUpdate(req.user._id, { $set: { name: req.body.name }}, { new: true }, function (err, User) {
if (err) {
console.log(err.toString());}
res.alert('Changed name');
console.log('changed name')
});
};
if (req.body.skills.length === 0){}
else {
User.findByIdAndUpdate(req.user._id, { $set: { skills: req.body.skills }}, { new: true }, function (err, User) {
console.log("Old Skills: " + User.skills.toString());
if (err) {
console.log(err.toString());}
console.log("New skills: " + User.skills.toString());
console.log('changed skills')
});
}
};
module.exports = profileController;
Which gets its data from this HTML form:
<!-- register container -->
<div class="container">
<form role="form" action="profile.html" method="post" style="max-width: 300px;">
<h2 class="form-heading">Your Profile</h2>
<input type="text" name="name" placeholder="Name" class="form-control" />
<input type="text" name="username" placeholder="Username" class="form-control" />
<input type="text" name="surname" placeholder="Last Name" class="form-control"/>
<input type="text" name="skills[]" placeholder="Your skills" class="form-control"/>
<button type="submit" class="btn btn-lg btn-primary btn-block">Save</button>
</form>
</div>
I'm very sorry for my bad code quality. This resulted from a very long day of working on it, but I simply couldn't figure out (even with tutorials and stack overflow) what went wrong.
The result is a 500 Internal Server Error.
Where is your PUT request? To update data, you need to use a PUT request. POST is for adding new entries.

Send email using php, http response erorr

I am having problem send email using php and jquery if some one can take a look and help me i would be thankful to him.
This is my HTML
<form id="contact" name="contact" method="post">
<h2>
<span>
Read This FREE Report
</span>
Discover How You Could Become a Successful Forex Trader In As Little As 72 Hours From Now (or Less)!
</h2>
<input type="text" id="name" placeholder="Name" name="name" required />
<input type="email" id="email" placeholder="Email" name="email" required />
<button type="submit">
Free Instant Access
</button>
</form>
Jquery
// Get the messages div.
var formMessages = $('#form-messages');
// Set up an event listener for the contact form.
$('form').submit(function (event) {
// Stop the browser from submitting the form.
event.preventDefault();
// Serialize the form data.
var formData = $('form').serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: 'contact_form.php',
data: formData
})
.done(function (response) {
$(formMessages).text("Your form has been send..");
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#name').val('');
$('#email').val('');
})
.fail(function (data) {
$(formMessages).text("Oops! An error occured and your message could not be sent");
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
Php
<?php
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
// Check that data was sent to the mailer.
if ( empty($name)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! Dogodio se problem za vašim zahtjevom. Molimo pokušajte opet.";
exit;
}
// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient = "email#hotmail.com";
// Set the email subject.
$subject = "Web contact from $name";
// Build the email content.
$email_content = "Person: $name\n";
$email_content = "Email: $email\n";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Došlo je do pogreške, nismo uspjeli poslati vašu poruku.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "Dogodio se problem za vašim zahtjevom. Molimo pokušajte opet.";
}
?>
And this is error i get:
Fatal error: Call to undefined function http_response_code() in /home2/speanut/public_html/freeforexreport.com/contact_form.php on line 35
Seems like your PHP Version is below 5.4. The http_response_code() function was introduced in PHP 5.4.
I would advice you to update for PHP 5.4 or higher. If you can not do that, you can use following compatibility code:
// For 4.3.0 <= PHP <= 5.4.0
if (!function_exists('http_response_code'))
{
function http_response_code($newcode = NULL)
{
static $code = 200;
if($newcode !== NULL)
{
header('X-PHP-Response-Code: '.$newcode, true, $newcode);
if(!headers_sent())
$code = $newcode;
}
return $code;
}
}
For more reference look at the following question.