sending json data response - json

I am trying to send a JSON response via HTTP but unfortunately, I don't see any response, I cant understand why really.
It looks like the response variable is not being sent.I am not sure the problem is that it is a JSON object or the way I am sending it.I am new to web development.
The requirement is to help user see the time and the name of the file which was usccessfully sent through.
var express = require('express');
var fs = require('fs');
var cors = require('cors');
var bodyParser = require('body-parser');
var multer = require('multer');
var app = express();
var upload = multer({ dest: 'uploads/' });
var Client = require('ssh2').Client;
const request = require('request');
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cors());
app.get('/', function(req, res){
console.log('GET /');
//var html = '<html><body><form method="post" action="http://localhost:3000">Name: <input type="text" name="name" /><input type="submit" value="Submit" /></form></body>';
var html = fs.readFileSync('index.html');
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(html);
});
app.post('/', upload.single('file'), function(req, res){
var response;
var time;
console.log('POST /');
console.dir(req.body);
// console.log(req.body.filename);
fs.writeFile('./uploads/' + req.body.filename, req.body.file,
function(err) { console.log(err)});
var conn = new Client();
conn.on('ready', function() {
console.log('Client :: ready');
conn.sftp(function(err, sftp) {
if (err) throw err;
// sftp.fastPut('./uploads/' + req.body.filename, '/data/' +
req.body.filename, function (err) {
// if (err) {
// console.log(err);
// throw err;
// }
// });
sftp.readdir('data', function(err, name) {
if (err) throw err;
console.dir(name);
var infoList = JSON.parse(JSON.stringify(name));
for(var index in infoList) {
var value = infoList[index];
time = value.attrs.mtime;
console.log(value.filename);
console.log(time);
response = JSON.stringify(value.filename);
}
conn.end();
});
});
}).connect({
host: 'ftp.amadeus.net',
port: 15022,
username: 'wtl001',
password: 'Wyamp309$'
});
res.writeHead(200, {'Content-Type': 'application/json', "Access-Control-
Allow-Origin": "*"});
res.json(response);
res.end("EOF");
});
port = 12811;
app.listen(port);
console.log('Listening at http://localhost:' + port);

Related

trouble in sending data through ajax to express server

I'm new to backend and I was having some trouble in sending data through vanilla ajax to my express server.
please tell me where am I going wrong
my ajax request:
var xhttp = new XMLHttpRequest();
xhttp.onload = function() {
};
xhttp.open("POST", "http://localhost:8080", true);
xhttp.withCredentials = true;
xhttp.send("name=abhishek");
my express server:
var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors({
credentials:true,
origin:'http://127.0.0.1:5500'
}));
var PORT = process.env.PORT || 8080;
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.get('/', function(req, res){
console.log(req.query);
});
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});
I'm receiving an empty object as the output in my console
There are few things to change.
The client is a POST request but in server side, it is a GET app.get(). Therefore, nothing displayed after request.
Also, Content-type needs to be set to inform server how it is going to parse the message. e.g. JSON/form-data
I assume you want to use POST, below is the change:
Backend:
Change method from app.get to app.post
Get the data from body instead of query
...
app.post("/", function (req, res) {
console.log(req.body); // data is in body instead of query
res.send("hi"); // send back response to frontend
});
...
Frontend:
Set content-type
var xhttp = new XMLHttpRequest();
xhttp.onload = function() {
alert(xhttp.responseText); // should receive hi
};
xhttp.open("POST", "http://localhost:8080", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.withCredentials = true;
xhttp.send("name=abhishek");

nodejs server app.post issue XML Parsing Error: syntax error Location: http://localhost:3000/get_messages Line Number 1, Column 1:

I followed a tutorial on YouTube to create a private user to user chat.
https://www.youtube.com/watch?v=Ozrm_xftcjQ
Everything on the chat works accept that i keep getting this Error:
XML Parsing Error: syntax error Location: http://localhost:3000/get_messages Line Number 1, Column 1:
using firefox developer edition and chrome. if i click the stack trace link i get the following xml error:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /get_messages</pre>
</body>
</html>
but i have no GET calls at all..
The code looks as follows:
server.js file
var port = process.env.PORT || 3000;
//creating express instance
var express = require("express");
var app = express();
//creating http instance
var http = require("http").createServer(app);
//app.use(express.static(__dirname));
//creating socket instance
var io = require("socket.io")(http);
//create body parser instance
var bodyParser = require("body-parser");
app.use(bodyParser.json());
//enable url encode for POST requests
app.use(bodyParser.urlencoded({ extended : true }));
//create instance of mysql
var mysql = require('mysql');
//create mysql connection
// connectionLimit: 100,debug: true
var connection = mysql.createConnection({
host: 'localhost',
user: 'xxx',
password: 'xxx',
database: 'chatio'
});
connection.connect(function(error){
if(error){
console.log(error);
return;
}
console.log('database connected');
})
//enable header request for post requests
app.use(function(request, result, next){
result.setHeader("Access-Control-Allow-Origin", "*");
next();
})
//create api to return all messages
app.post("/get_messages", function(request, result){
console.log(request);
console.log(result);
connection.query("SELECT * FROM chat_messages WHERE (`from_id` = '"+request.body.sender+"' AND `to_id` = '"+request.body.receiver+"') OR (`from_id` = '"+request.body.receiver+"' AND `to_id` = '"+request.body.sender+"')", function(error, messages){
if(error){
console.log(error);
return;
}
console.log(messages);
//response will be in JSON
result.end(JSON.stringify(messages));
});
})
io.on("connection", function(socket){
socket.on("send_message", function(data){
//send event to receiver
var socketId = users[data.receiver];
io.to(socketId).emit("new_message", data);
//save in database
connection.query("INSERT INTO chat_messages (`from_id`,`to_id`,`message`) VALUES ('"+data.sender+"', '"+data.receiver+"', '"+data.message+"')", function(error, result){
if(error){
console.log(error);
return;
}
console.log('message saved');
});
})
})
http.listen(port, function(){
console.log("server started");
})
inde.php file code as follows:
//creating io connection
var io = io("http://localhost:3000");
var receiver = "johnny";
var sender = "steven";
function onUserSelected(){
$.ajax({
url: "http://localhost:3000/get_messages",
method:"POST",
cache: false,
data: {
"sender" : sender,
"receiver" : receiver
},
dataType: "json",
success: function(response){
var messages = response; //JSON.parse();
var html = "";
for(var i = 0; i < messages.length; i++){
html += "<li>" +messages[i].from_id + " says: " + messages[i].message + "</li>";
document.getElementById('messages').innerHTML += html;
}
}
});
return;
}
}
i figured it out..
the problem comes from this line:
result.end(JSON.stringify(messages));
I dont exactly understand why, but i changed it to
result.send(JSON.stringify(messages));
and now the bug is gone

Node.js, how do i take HTML form text input and direct it to a local file

I am trying to take some very simple text input through a form and direct it to a .txt file. not getting much luck and am way out of my depth, any help appreciated.
I have tried a few different ways but atm i am trying to GET the input, turn this into json data and send directly to the file.
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var http = require('http');
var fs = require('fs');
var passport = require('passport');
var passportLocal = require('passport-local');
var expressSession = require('express-session');
var expressValidator = require('express-validator')
//routes setup
var index = require('./routes/index');
var homepage = require('./routes/homepage');
var login = require('./routes/login');
var charitySignUp = require('./routes/charitySignUp');
var about = require('./routes/about');
var contactUs = require('./routes/contactUs');
var charityHomepage = require('./routes/charityHomepage');
var chat = require('./routes/newsFeed');
var ticket = require ('./routes/ticket');
var app = express();
require('./public/configure/passport');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
//middleware
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
//app.use(session({secret: 'mySecret', resave: false, saveUninitialized:
false}));
//app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));
//routes + backend js file
app.use('/', index);
app.use('/login', login);
app.use('/homepage', homepage);
app.use('/charitySignUp', charitySignUp);
app.use('/about', about);
app.use('/contactUs', contactUs);
app.use('/charityHomepage', charityHomepage);
app.use('/chat', chat);
app.use('/ticket', ticket);
/ 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;
Ticket.js - backend code
var express = require('express');
var router = express.Router();
var fs = require('fs');
router.get('/', function (req, res, next) {
res.render('ticket');
});
router.get('/insert', function (req, res) {
var issue = req.query.issue;
var email = req.query.email;
fs.appendFile("my_file.txt", JSON.stringify(email + issue), function (err) {
if (err) throw err;
console.log('updated');
});
});
module.exports = router;
form in .EJS file.
<form class="form-signin" action="/insert" method="get">
<h2 class ="text" class="form-signin-heading">Ticket form</h2>
<label class="sr-only"><b>email</b></label>
<input type="Email" class="form-control" placeholder="Enter email you would like your response directed" name="email" required>
<label class="sr-only"><b>Issue</b></label>
<input type="text" class="form-control" placeholder="type here" name="issue" required>
<button type="submit" class="btn btn-lg btn-primary btn-block">Submit</button>
</form>

Return undefined answer from multer

I am using multer in my nodejs application for uploading files. And angularjs for the front end part. Once I click upload image, on the console I am getting undefined answer. Can any one help me to solve the problem.
Here I am pasting the code.
server.js
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var bodyParser = require('body-parser');
var path = require('path');
var fs = require('fs');
var spawn = require('child_process').spawn;
var multer = require('multer');
var storage = multer.diskStorage({
destination:function(req,file,cb){
cb(null,'public/upload/');
},
filename:function(req,file,cb){
cb(null,file.originalname);
}
});
var upload = multer({storage: storage});
app.set('views', __dirname + '/views');
app.use(bodyParser.json());
var urlencodedParser = bodyParser.urlencoded({ extended: true });
app.use(express.static('public'));
app.get('/',function(req,res){
res.render('index',{ title: 'Upload image' });
});
app.post('/loadImage',upload.any(),function(req, res) {
console.log(req.files);
console.log("Inside post");
});
http.listen(8080,'0.0.0.0',function(){
console.log('listening on 8080');
})
And here is my app.js angularjs code
var app = angular.module('app',['ui.router','ui.bootstrap','ngAnimate']);
$scope.img={};
app.controller('Ctrl',function ($scope,$http){
$scope.loadImage = function(){
$http.post('/loadImage',$scope.img).success(function(data){
console.log('Posted successfully');
}).error(function(data){
console.error('error');
})
};
And my HTML code:
<form ng-submit="loadImage()" enctype="multipart/form-data">
<input type="file" name="file" multiple />
<input type="submit" value="Upload Image" name="submit" />
</form>
On the console I am getting Undefined and Inside post. And on the browser console I am getting posted successfully Can any one please help me to solve this. Instead of undefined I should get loaded file information.
This how i used Multer to upload an image
var multer = require('multer');
exports.loadImage = function (req, res) {
var upload = multer({
inMemory: true,
limits: {fileSize: 1024 * 1024 }
}).single('newPicture');
upload(req, res, function (uploadError) {
if (uploadError) {
return res.status(400).send({ message: 'errorUploadingPicture' });
}
else {
var profileImage = 'No data uploaded';
// this is where the photo data is
if (req.file && req.file.buffer) {
profileImage = req.file.buffer;
}
return res.json(profileImage );
}
});
};
This is all assuming you are sending your file correct
try
var uploadType = upload.any()
and change
app.post('/loadImage',upload.any(),function(req, res) {
console.log(req.files);
console.log("Inside post");
});
to
app.post('/loadImage',uploadType,function(req, res) {
console.log(req.files);
console.log("Inside post");
});
if you are attempting to only get one file at a time then instead,
var uploadType = upload.single('file')
app.post('/loadImage',uploadType,function(req, res) {
console.log(req.files);
console.log("Inside post");
});

How to connect static HTML and CSS files to Node.js application?

I try to show a (static) HTML webpage via Heroku. I have followed this tutorial: https://www.youtube.com/watch?v=gAwH1kSODVQ but after many attempts it is still not working.
I'm rather new to coding, so if you can give concrete examples that would be great!
The following files have been pushed to heroku:
server.js
package.json
Procfile.js
(folder) public with index.html, main.css
//Server.js file:
var express = require('express'); //require express module in server.js file
var app = express();
var mongojs = require('mongojs');
var db = mongojs('birthdaylist', ['birthdaylist']);
var bodyParser = require('body-parser');
var http = require('http');
var port = Number(process.env.PORT || 3000);
app.use(express.static(__dirname + '/public')); //connect to html file
app.use(bodyParser.json());
app.get('/birthdaylist', function(req, res) {
console.log("The server has received a GET request.")
db.birthdaylist.find(function(err, docs){
console.log(docs);
res.json(docs);
});
});
app.post('/birthdaylist', function(req, res){
console.log(req.body);
db.birthdaylist.insert(req.body, function (err, doc){
res.json(doc);
});
});
app.delete('/birthdaylist/:id', function(req, res){
var id = req.params.id;
console.log(id);
db.birthdaylist.remove({_id: mongojs.ObjectId(id)}, function(err, doc){
res.json(doc);
});
});
app.listen(port, function () {
});
you should use:
app.listen(%PORT_NUMBER%, function () {
// some code here
});
Instead of:
var server = http.createServer(function(req, res){
res.writeHead(200, {'Content-Type':'text/html'});
res.end('<h6>Hello worldsfasfd!</h6>');
});