This is the route code:
router.get('/compose/:ID', function(req, res, next) {
var random = Math.floor((Math.random() * 1000000) + 1);
console.log("random = " + random);
res.render('compose', { random: random, Id:req.params.ID });
})
.post(function(req, res, next) {
var to = '917985754084';
var from = 'GrumpyText';
var text = req.body.OTP;
console.log(text);
nexmo.message.sendSms(from, to, text, function(err,success){
if(success)
console.log("SMS sent successfully!");
else {
console.log("error");
}
});
});
This is the handlebar code:
<main role="main" class="container">
<div class="jumbotron">
<h1>List of Contacts</h1>
<table class="table table-striped">
<thead>
<tr>
<th scope="col"></th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<form method="post" enctype="multipart/form-data">
<tr>
<td><input type="text" name="OTP" class="form-control" value="Hi. Your OTP is : {{random}}"></td>
<td></td>
</tr>
<tr>
<td><button type="submit" class="btn btn-lg btn-primary btn-block">Submit</button>
</td>
</tr>
</form>
</tbody>
</table>
</div>
</main>
Its coming to the route but the console is not printing the 'text'. aka console.log(text) means req.body.OTP is not printing anything. Earlier it was printing undefined.
Could you please rectify where it is stucking perhaps?
The issue you are hitting is body-parser doesn't handle multipart/form-data.
There are several options, but one of those is multer.
\* add these for multi-part*\
var multer = require('multer')
var upload = multer();
\* other code *\
router
.get('/compose/:ID', function (req, res, next) {
var random = Math.floor(Math.random() * 1000000 + 1);
console.log('random = ' + random);
res.render('compose', { random: random, Id: req.params.ID });
})
.post('/compose/:ID', upload.none(), function (req, res, next) {
var to = '917985754084';
var from = 'GrumpyText';
var text = req.body.OTP;
nexmo.message.sendSms(from, to, text, function (err, success) {
if (success) console.log('SMS sent successfully!');
else {
console.log('error');
}
});
});
Related
I have this problem, it turns out that I need to access the header data that is enclosed in red (Form Data), however, I can only access the information in orange (Request Headers). I need it to send information from the pdf file that is rendered on the frontend (nextjs). The library I'm using for the pdf is Kendo React, and the "proxyURL" prop is the only thing, in my opinion, that helps me send information to the backend.
Request Headers and Form Data
Target Proxy
This is the capture of the req.headers console.log, what I need is out of it, I have been seeing more than 4 hours how to access Form Data. Thanks You Very Much
Log req.headers
Attached the server code the proxy is on line 67
const express = require('express');
const { ApolloServer } = require('apollo-server-express');
const typeDefs = require('./db/schema');
const resolvers = require('./db/resolvers');
const {
GraphQLUpload,
graphqlUploadExpress, // A Koa implementation is also exported.
} = require('graphql-upload');
const jwt = require('jsonwebtoken')
const conectarDB = require('./config/db');
const { bootstrap: bootstrapGlobalAgent } = require('global-agent');
const cors = require("cors");
require('dotenv').config({path: 'variables.env'});
conectarDB();
bootstrapGlobalAgent();
// const corsOptions = {
// origin: process.env.PAGINA,
// optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
// credentials: true
// }
async function startServer() {
const server = new ApolloServer({
typeDefs,
resolvers,
cors: {
credentials:true,
origin: process.env.PAGINA,
optionsSuccessStatus:200
},
context: ({req}) => {
// // console.log(req.headers['authorization']);
const token = req.headers['authorization'] || '';
// console.log("headers", req.headers);
if (token) {
try {
const usuario = jwt.verify(token.replace('Bearer ', ''), process.env.SECRETA )
console.log(usuario);
return {
usuario
}
} catch (error) {
console.log("HUBO UN ERROR");
console.log(error.message);
}
}
}
});
await server.start();
const app = express();
// process.env.PAGINA
try {
app.use(graphqlUploadExpress());
app.use(express.static('public'));
// PROXY
app.all("/pdf", (req, res, ) => {
console.log("header", req.headers);
res.send('Data')
})
server.applyMiddleware({ app });
app.use(cors({
origin: process.env.PAGINA,
credentials: true,
optionsSuccessStatus:200
}))
// app.use((req, res, next) => {
// res.header("Access-Control-Allow-Origin", "*");
// res.header(
// "Access-Control-Allow-Headers",
// "Origin, X-Requested-With, Content-Type, Accept, Authorization"
// );
// if (req.method == "OPTIONS") {
// const awa = res.status(200).json({})
// const data = JSON.stringify(awa);
// console.log("data", data);
// console.log("uwuw", res.status(200).json({}));
// return res.status(200).json({});
// }
// next();
// });
// app.use(cors(corsOptions))
// await new Promise(r => app.listen({ port: process.env.PORT || 4000 }, r));
// console.log(`🚀 Server ready at http://localhost:${process.env.PORT || 4000}${server.graphqlPath}`);
// Arrancar el servidor
app.listen({ port: process.env.PORT || 4000}, () => {
console.log(`Servidor corriendo http://localhost:${process.env.PORT || 4000}${server.graphqlPath}`);
})
} catch (error) {
console.log(error);
}
// This middleware should be added before calling `applyMiddleware`.
}
startServer();
And the PDFExport component
<>
<PDFExport forceProxy={true} proxyURL={`http://localhost:4000/pdf`} proxyTarget={`Data`} ref={pdfExportComponent} paperSize="A4" fileName="archivo" key="archivo" >
<div className="body__container" ref={container}>
<header className="header__container">
<h1 className="header__title">PRESUPUESTO</h1>
<div className="header__image"></div>
</header>
<div className="section__body">
<p>Datos del paciente</p>
<h4>
Nombre: <label> {nombre}</label>
</h4>
<h4>
Apellido: <label>{apellido} </label>
</h4>
<h4>
Tipo doc: <label>{tipDoc}</label>
</h4>
<h4>
Numero doc: <label>{docNum}</label>
</h4>
<h4>
Fecha:{" "}
<label>
{dia}-{String(mes).length === 1 ? `0${mes}` : mes}-{year}
</label>
</h4>
</div>
<div className="table__container">
<Table size="sm">
<thead>
<tr>
<th className="table-cabecera-id">N°</th>
<th className="table-cabecera-categoria">CategorÃa</th>
<th className="table-cabecera-tratamiento">Tratamiento</th>
<th className="table-cabecera">Cantidad</th>
<th className="table-cabecera">C/U</th>
<th className="table-cabecera">Descuento</th>
<th className="table-cabecera">Costo</th>
</tr>
</thead>
<tbody>
{presupuesto.map((item, index) => (
<tr key={item.id}>
<td className="table-elementos">{index + 1}</td>
<td className="table-elementos" lang="es">
{item.categoria}
</td>
<td className="table-elementos" lang="es">
{item.tratamiento}
</td>
<td className="table-elementos">{item.cantidad}</td>
<td className="table-elementos">{item.precio}</td>
<td className="table-elementos">{item.descuento}</td>
<td className="table-elementos">
{item.precio * item.cantidad - item.descuento}
</td>
</tr>
))}
</tbody>
</Table>
</div>
<div className="footer">
<div className="footer__resumen">
<h4>Subtotal:</h4>
<label>S/{sumaSub}</label>
</div>
<div className="footer__resumen">
<h4>Descuento:</h4>
<label>{sumaDesc}%</label>
</div>
<div className="footer__resumen">
<h4>Total: </h4>
<label>S/{montoTotal}</label>
</div>
</div>
<div className="body__doctor">
<h4>Atentamente, Dr. {doctor.nombre} {doctor.apellido}.</h4>
</div>
<div className="footer__contacto">
<div className="footer__contacto-datos">
<h4 className="datos__title">
ODONTO<label>TRENDS</label>
</h4>
<h4>92034933838</h4>
<h4>
Direccion:{" "}
<p className="datos__direccion">
Av. Angelica Gamarra 561 Urb El Trebal - Los Olivos LIMA
</p>
</h4>
<h4>
Telefono: <p>920411227</p>
</h4>
</div>
<div className="footer__contacto-sociales">
<h4 className="footer__contacto-title">Redes sociales</h4>
<div className="sociales__container">
<h4>Odontotrends</h4>
<div className="sociales-facebook"></div>
</div>
<div className="sociales__container">
<h4>odonto_trends</h4>
<div className="sociales-instagram"></div>
</div>
<div className="sociales__container">
<h4>977 182 001</h4>
<div className="sociales-whatsapp"></div>
</div>
</div>
</div>
</div>
</PDFExport>
</>
A POST request puts the data in the request body, not as a header. Your request handler that is handling that POST request will need to read and parse the body of the request.
If this is a form post and you're using Express, then you would install the appropriate middleware - probably app.use(express.urlencoded()). Then your form values would be in req.body.
If the data is an uploaded file, then you may need additional middleware to parse the mime body such as multer.
I am new to node.js. I am created small example, now I want to delete multiple rows based on checkbox condition. I have one table of checkboxes as last column. I want delete checked checkbox rows when click on button.
Jade code is
<section class="get">
<h3>Get Data</h3>
LOAD DATA
<div>
<table>
{{# each items }}
<article class="item">
<tr>
<td>{{ this.title }}</td>
<td>{{ this.content }}</td>
<td>{{ this.author }}</td>
<td>{{ this._id }}</td>
<form action="/check" method="post">
<td><input type="checkbox" id="chk" name="chk" ></td>
</article>
</tr>
{{/each}}
<button>check</button>
</form>
</table>
</td>
</section>
Back end code is
router.get('/get-data', function(req, res, next) {
var resultArray = [];
mongo.connect(url, function(err, db) {
assert.equal(null, err);
var cursor = db.collection('user-data').find();
cursor.forEach(function(doc, err) {
assert.equal(null, err);
resultArray.push(doc);
}, function() {
db.close();
res.render('index', {items: resultArray});
});
});
});`
router.post('/check', function(req, res, next) {
// var id = req.body.id;
console.log("check value");
console.log(req.body.chk);
req.body.chk=Boolean(req.body.chk);
for(i=0; i<req.body.chk;i++){
if(req.body.chk==true){
res.redirect('/');
}
else{
res.send("checkbox is not checked");
}
}
});
Hi,
I'm trying to get value from mongoose and populate textbox with it. So basically when I click Edit button I would like the name of the department appear in Department name textbox. I tried multiple things but failed. ($('#departmentName').val(department.name) for example) How can I do it properly? Thank you.
my department handlebar
<h2>Departments List</h2>
<div class="row">
<div class="col-lg-12">
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<form method="POST" action="/departments/create_department">
<td><input class="form-control" type="text" placeholder="Department Name" name="departmentName" id="departmentName"></td>
<td><button class="btn btn-primary" type="sumit">Add Department</button></td>
</form>
<td><button class="btn btn-info">Update</button></td>
<td><button class="btn btn-info">Clear</button></td>
</tr>
{{#each departments}}
<tr>
<form method="POST" action="/departments/remove_department/{{_id}}?_method=DELETE">
<td>{{name}}</td>
<td><button class="btn btn-danger" type="submit">Remove</button></td>
</form>
<form method="GET" action="/departments/edit_department/{{_id}}?">
<td><button class="btn btn-warning" value={{id}} type="submit">Edit</button></td>
</form>
</tr>
{{/each}}
</tbody>
</table>
</div>
</div>
my department controller
var express = require('express');
var router = express.Router();
var passport = require('passport');
var mongoose = require('mongoose');
var Departments = require('../models/department');
var User = require('../models/user');
// List of departments
router.get('/add_department', userAuthenticated, function(req, res, next) {
Departments.find(function(err, departments) {
if (err) {
throw err;
}
res.render('add_department', {title:'Add New Department', departments: departments, name: departments.name, id: departments._id})
})
});
// Edit department
router.get('/edit_department/:id', userAuthenticated, function(req, res, next) {
var departmentName = "";
Departments.findById(req.params.id).exec(function(err, department) {
if (err) {
throw err;
} else {
$('#departmentName').val(department.name);
res.redirect('/departments/add_department');
}
})
});
You could try changing the input field in handlebars to display the value you queried from mongoose
change this
<td><input class="form-control" type="text" placeholder="Department Name" name="departmentName" id="departmentName"></td>
to this
<td><input class="form-control" type="text" value={{name}} name="departmentName" id="departmentName"></td>
Then take this out of the routes
$('#departmentName').val(department.name);
UPDATE:
So something like this
// List of departments
router.get('/add_department', userAuthenticated, function(req, res, next) {
// grab the deparment from the req
var departmentFromEdit ="";
if(req.query.dn){
departmentFromEdit = req.query.dn;
}
Departments.find(function(err, departments) {
if (err) {
throw err;
}
res.render('add_department', {title:'Add New Department', departments: departments, name: departments.name, id: departments._id})
})});
// Edit department
router.get('/edit_department/:id', userAuthenticated, function(req, res, next) {
var departmentName = "";
Departments.findById(req.params.id).exec(function(err, department) {
if (err) {
throw err;
} else {
departmentName = encodeURI(department.name);
// dn for departmentName or defaultName
res.redirect('/departments/add_department?dn=' + departmentName);
}
})});
I'm new to NodeJs. Now I'm trying socket.io. I want to build website like Zopim(https://www.zopim.com/). Now I'm struggling with : client(A) should get helpline from one admin only and to prevent other admins to chat with client(A).
This is server.js
var app = require('express')();
var bodyParser = require('body-parser');
var mysql = require("mysql");
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.use(require("express").static('data'));
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
/* Creating MySQL connection.*/
var con = mysql.createPool({
host : 'localhost',
user : 'root',
password : '',
database :'Chat_tryout'
});
var insertRecord = 'Insert into mytable(socketid,receiver,message)value(?,?,?)';
app.get("/",function(req,res){
res.sendFile(__dirname + '/index.html');
});
var msg={};
io.on('connection', function(socket){
console.log(socket.id + "connected");
socket.on('message',function(msg){
console.log('user' +this.id+ 'sent message"'+ msg +'"');
//console.log(" admin id " + io.sockets.connected[socketid]);
con.getConnection(function(err, connection) {
var message=msg;
var socketid=" ";
con.query( insertRecord,[socketid,socket.id,msg], function(err, res) {
if(err){
console.log("error:" + err);
}else
console.log ("inserted"+ socket.id +"message"+ msg);
//res.end(``);
});
});
app.post('/get_data', function (req, res) {
var msg=req.body.name;
var toid = req.body.toid;
//var socketid = this.socket.sessionid;
//console.log(socketid);
console.log(toid);
io.to(toid).emit('mymessage',msg);
con.getConnection(function(err,connection){
var message=msg;
con.query( insertRecord,[socketid,toid,msg], function(err, res) {
if(err){
console.log("error:" + err);
}else
console.log ( "inserted "+ socket.id +" message "+ msg);
});
});
});
});
socket.on('disconnect', function() {
console.log('client socketio disconnect!');
});
app.get('/api/getalldata', function(req,res){
con.getConnection(function(err,connection){
con.query( 'select * from mytable', function(err, rows) {
if(err){
console.log("error:" + err);
}else
console.log ("success");
res.json(rows);
});
});
});
});
http.listen(8080,function(){
console.log("Listening on http://127.0.0.1:8080/");
});
Index.html :
(ADMIN PAGE)
<html ng-app="sample">
<head>
<title>Connecting Node.js app to MySql</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script type="text/javascript">
var app = angular.module('sample',[]);
app.controller('sample', function ($scope,$http,$timeout) {
$scope.data_server={};
$scope.socketid={};
var TypeTimer;
var TypingInterval = 1000;
$scope.keyup = function() {
$timeout.cancel(TypeTimer);
TypeTimer=$timeout( function(){ get_data(); }, TypingInterval);
};
$scope.keydown = function(){
$timeout.cancel(TypeTimer);
};
function get_data(){
var name=$scope.name;
var toid = $scope.toid;
$http.post('/get_data',{name:name,toid:toid}).success(function(data, status, headers, config) {
// $scope.data_server=data;
}).error(function(data, status) {
//alert("Connection Error");
});
}
$scope.getalldata = function(){
$http.get('/api/getalldata')
.success(function(data) {
$scope.data_server = data;
// console.log(data);
})
.error(function(err) {
console.log('Error: ' + err);
});
};
});
</script>
</head>
<body ng-controller="sample">
<div class="container">
<div id="name-group" class="form-group">
<h2>ADMIN</h2>
<ul id="messages"></ul>
<br/>
<input type="text" class="form-control" ng-model="name" placeholder="Type here and check the Title in Tab"/>
<input type="text" class="form-control" ng-model="toid" ng-keyup="keyup()" ng-keydown="keydown()" ng-blur="blur()" ng-change="change()"/>
{{toid}}
<br/>
</div>
<div class="table-responsive">
<table class="table table-hover"ng-repeat="data in data_server" >
<thead>
<tr>
<th>From</th>
<th>Message</th>
</thead>
<tbody>
<tr>
<td>{{data.receiver}}</td>
<td>{{data.message}}</td>
<!-- <td><input type="text" value="{{data.receiver}}"><td>
<td><input type="text" ng-model="reply" ng-keyup="submit()"></td>-->
</tr>
</tbody>
</table>
</div>
<div class="rows">
<div class="col-md-12">
<div class="data" >
<!---{{ data_server}}--->
<hr/>
</div>
<div ng-show="data_server.length == 0" >
<div class="alert alert-info" >
<p class="text-center" >
Sorry, Right now we don't have any results for you.
</p >
</div >
</div >
</div>
</div>
<div class="rows">
<button class="btn btn primary" ng-click="getalldata()">Get Messages</button>
<div class="form-row form-last-row">
</div>
</div>
</div>
</body>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io.connect("http://localhost:8080");
socket.on('message', function(msg){
$('#messages').append($('<li>').text(msg));
});
I'm having html front end for client where they emit and receive messages using:
var socket = io.connect("http://localhost:8080");
$('form').submit(function(){
socket.emit('message', $('#message').val());
$('#message').val('');
return false;
});
socket.on('mymessage', function(msg){
$('#messages').append($('<li>').text(msg));
});
**app.js** Code
app.get('/', function (req, res) {
res.render('index', {
data: docsData,
title: "EJS example",
header: "Some users"
});
});
app.post('/', function (req, res) {
var jname= req.body.firstname;
var lname= req.body.lastname;
var jemail= req.body.email;
var collection = dbConnect.collection('users');
var document={name:jname, lastname:lname, email:jemail};
collection.insert(document, {w: 1}, function(err, records){
console.log("Record added as "+records[0]._id);
});
dbConnect.collection("users").find({"name":jname}).toArray(function(err, docsData) {
console.log('checking error',err, docsData);
res.render('index', {
data: docsData,
title: "AJT Family",
header: "Some users"
});
});
});
**html code**
<div align="center" ng-controller="FormCtrl">
<form name="form" ng-submit="submitForm()" novalidate>
<table>
<tr><td>Name:</td>
<td>
<input id="firstname" type="text" ng-model="regform.firstname" name="firstname" required="" />
</td>
<td>
<div ng-show="form.$submitted || form.firstname.$touched">
<div ng-show="form.firstname.$error.required">Enter your name.</div>
</div>
</td>
</tr>
<tr>
<td>Last Name: </td>
<td>
<input id="lastname" name="lastname" type="text" ng-model="regform.lastname" required>
</td>
<td>
<div ng-show="form.$submitted || form.lastname.$touched">
<div ng-show="form.lastname.$error.required">Enter your Last name.</div>
</div>
</td>
</tr>
<tr>
<td>E-mail:</td>
<td><input id="email" type="email" ng-model="regform.email" name="uEmail" required="" /></td>
<td>
<div ng-show="form.$submitted || form.uEmail.$touched">
<span ng-show="form.uEmail.$error.required">Enter your email.</span>
<span ng-show="form.uEmail.$error.email">This is not a valid email.</span>
</div>
</td>
</tr>
</table>
<input type="button" ng-click="reset(form)" value="Reset" />
<input type="submit" ng-disabled="!form.$valid" value="Save" />
<p id="hu"></p>
</form>
</div>
<%if(data) {%>
<h1>Users</h1>
<% data.forEach(function(user){ %>
<br>
<table>
<tr><td>Name: </td><td><%= user.name %> <%= user.lastname %></td></tr>
<tr><td>Email: </td><td><%= user.email %></td></tr>
</table>
<% }) %>
<% } %>
</body>
</html>
**javascript**
var result;
var app = angular.module('formExample', []);
app.controller('FormCtrl', function ($scope, $http) {
$scope.data = {};
$scope.submitForm = function() {
formData = $scope.regform;
console.log("posting data....");
var request = $http({ url: '/',data: $scope.regform, method: 'post' });
console.log(formData);
};
});
here I can save data on mongodb using expressjs. I need to display data after form submission. Here nothing is displaying after form submission. How to display that saved content in html using embedded Javascript.
What you'll want to do is change your res.render() call to do something like this:
res.render('index', {
data: docsData,
title: 'AJT Family',
header: 'Some Users',
body: req.body, // This is your form data as a JSON object.
});
Then, in your index template, you'll have access to your form data to display however you want, if you're using Jade, for instance, you might want to say like:
h1 Data!
p #{body}