Node.js - jQuery. Get PDF from server and display on front-end - javascript

I'm bit stuck here. My intent is to first get all files (filenames) from a static folder + subfolders and list all on front-end.
When user clicks one of the filenames (mostly pdf's), the server returns the selected items content.
I'm able to send the pdf data as binary to front-end, but how could I display the data in a new tab with js/jQuery?
so far..
Server.js -
// Importing and initializing npm/node plugins
var app = require('express')();
var server = require('http').createServer(app);
var logger = require('morgan');
var bodyParser = require('body-parser');
var pdf = require('express-pdf');
var cors = require('cors');
var fs = require('fs');
// Import config settings
var config = require('./config.json');
app.use(logger('dev'));
// Allow application/x-www-form-urlencoded and application/json
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json({
limit: '50mb'
}));
app.use(cors());
app.use(pdf);
app.get('/getfiles', function (req, res) {
var dir = config.sourceDir;
var foundFiles = [];
fs.readdir(dir, function (err, files) {
if (err) {
console.log('Error reading ' + dir);
process.exit(1);
}
console.log('Listing files in Directory ' + dir);
files.forEach(function (f) {
foundFiles.push(f);
});
res.json(foundFiles);
});
});
app.post('/showfiles', function (req, res) {
var file = req.body.filename;
var dir = config.sourceDir;
fs.readFile(dir + file, function (err, data) {
res.contentType('application/pdf');
res.send(data);
});
});
// Open server in port
server.listen(config.port, function () {
console.log('Server listening on port: ' + config.port);
});
module.exports = app;
On front-end -
$(function () {
getFiles();
});
function getFiles() {
$.ajax({
type: "GET",
url: "http://localhost:3000/getfiles",
contentType: "application/json; charset=utf-8",
crossDomain: true,
dataType: "json",
success: function (data, status, jqXHR) {
if (data) {
$.each(data, function (index, value) {
$("#listContainer1").append("<li><a href='#' onclick='showFile(this)'>" + value + "</a></li>");
});
}
},
error: function (jqXHR, status) {
console.log("Error fetching data");
}
});
}
function showFile(file) {
$.ajax({
type: "POST",
data: JSON.stringify({
"filename": $(file).text()
}),
url: "http://localhost:3000/showfiles",
contentType: "application/json; charset=utf-8",
crossDomain: true,
dataType: "application/pdf",
success: function (data, status, jqXHR) {
if (data) {
var file = new Blob([data], {
type: 'application/pdf'
});
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
}
},
error: function (jqXHR, status) {
console.log("Error showing file");
}
});
}
But this keeps falling into the "Error showing file" pit. :(
EDIT:
The first error was corrected by removing the "application/pdf" from post, but now its opening an empty pdf with correct page limit

On the server, change the file fetch code to this:
app.get('/showfiles/:filename', function (req, res) {
var options = {
root: config.sourceDir
};
var fileName = req.params.filename;
res.sendFile(fileName, options, function (err) {
if (err) {
// Handle error
} else {
// Handle success
}
});
});
So I switched the method to GET and used the built-in sendFile method in Express. Then on the front end it's much easier. You can get rid of the showFile function and just update the getFiles function:
function getFiles() {
$.ajax({
type: "GET",
url: "http://localhost:3000/getfiles",
contentType: "application/json; charset=utf-8",
crossDomain: true,
dataType: "json",
success: function (data, status, jqXHR) {
if (data) {
$.each(data, function (index, value) {
$("#listContainer1").append('<li>' + value + '</li>');
});
}
},
error: function (jqXHR, status) {
console.log("Error fetching data");
}
});
}
Code has not been tested and most likely has mistakes, but should give you a gist of another way you can tackle the problem.

Related

Express js does not return data after success to Ajax call

I am trying to store the data from client end javascript to server end express js after storing returning some data. I can receive the data at express API userdetail function but unable to return to ajax. Please can I get help?
$.ajax({
url: "http://localhost:8080/api/save_user/",
type: "POST",
crossDomain: true,
data: { name: 'Justin', number: '662***' },
dataType: "json",
contentType: "application/json",
success: function (response) {
var resp = JSON.parse(response)
},
error: function (xhr, status) {
alert("error");
}
});
Express Js server side
const express = require('express');
const path = require('path')
const os = require('os');
const app = express();
var bodyParser = require('body-parser')
app.use(bodyParser.json())
app.post('/api/save_user', (req, res) => {
Usermodel.saveData(req.body.name,req.body.number)
.then(function (userdetail) {
res.send({ success: true, data: userdetail });
})
.catch(next);
})

simple multipart file upload with express.js and multer with ajax

I don't get any errors. The folder uploads has chmod 777.
Backend:
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now())
}
});
var upload = multer({ storage: storage,
limits: { fileSize: '50mb' }}).single('photo');
router.post('/bild',function(req,res){
console.log("REQ",req); //file is there in the body
upload(req,res,function(err) {
if(err) {
return res.end("Error uploading file.");
}
res.end("File is uploaded");
});
});
Frontend:
$("#formular").submit(function (e) {
e.preventDefault();
var form = $(this)[0];
var formData = new FormData(form);
console.log(formData)
$.ajax({
type: "POST",
url: "/users/bild",
data: formData,
processData: false,
"content-type": "application/x-www-form-urlencoded",
success: function(r){
console.log("result",r)
},
error: function (e) {
console.log("some error", e);
}
});
});
But no files were uploaded. I also tried to get the get the file and append it to formData before sending - same effect.
For the front end, contentType must be set to false to use a formdata object in jQuery.ajax, also $(this)[0] === this
$("#formular").submit(function (e) {
e.preventDefault();
var formData = new FormData(this);
console.log(formData)
$.ajax({
type: "POST",
url: "/users/bild",
data: formData,
processData: false,
contentType: false,
success: function(r){
console.log("result",r)
},
error: function (e) {
console.log("some error", e);
}
});
});

ExpressJS does not seem to work with ajax calls

I'm trying to figure out Node.js to use as an api to do GET, POST, etc. I've been stuck trying to figure out why this post is not working.
My ajax call:
$.ajax({
method: "POST",
contentType: 'application/json',
dataType: 'json',
url: "localhost:8000/login",
data: JSON.stringify({user:"john", pass:"123"}),
error: function () {
alert('error');
},
success: function (data) {
alert('success');
}
});
In my express:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/login', function (req, res) {
var user = req.body.user;
var password = req.body.pass;
if(user == 'john' && password == '123') {
res.status(200);
} else {
res.status(401);
}
});
app.listen(8000, function () {
console.log('Example app listening on port 8000!');
});
Any help is greatly appreciated.
you should return some response from your express code, also response should be ended especially in case of just sending only the status code like res.status(401);
app.post('/login', function (req, res) {
var user = req.body.user;
var password = req.body.pass;
if(user == 'john' && password == '123') {
res.status(200).json({t:1});
} else {
res.status(401);
}
res.end();
});
This work for me:
$.ajax({
type: "POST",
contentType: 'application/json',
dataType: 'json',
url: "/login",
data: JSON.stringify({user:"john", pass:"123"}),
error: function (err) {
console.log(err);
alert('error');
},
success: function (data) {
alert('success');
}
});
app.post('/login', function (req, res, next) {
var user = req.body.user;
var password = req.body.pass;
if(user == 'john' && password == '123') {
res.status(200).json({s: 1});
} else {
res.status(401).json({e: 2});
}
});
var json = JSON.stringify({user:"john", pass:"123"});
$.ajax({
dataType: 'json',
type: "POST",
url: "/login",
data: json
}).done(function(data){
console.log("works fine");
});
Should work for an Ajax post function, sending the data to the node server.
The url needs to match the url of the app.post in the node server file, you don't need localhost in front of it.
ContentType is also not necessary and I made the json object outside of the Ajax call instead of setting it inside the Ajax call.
var express = require('express');
var parser = require('body-parser');
var app = express();
var port = 8000;
app.use(parser.urlencoded({extended: false}));
app.use(parser.json());
app.use(express.static('public'));
app.post('/login', function (req, res) {
var user = req.body.user;
var password = req.body.pass;
if(user == "john" && password == "123") {
res.status(200);
} else {
res.status(401);
}
});
var server = app.listen(port, function () {
var host = server.address().address
var port = server.address().port
console.log("App listening at http://%s:%s", host, port);
});
And that should work for the node server itself.
I set the server running, so you can always keep track of what port it's listening on, so you don't need to bother scrolling down to change the port, just change the port at the top of your file.
Further the /login was looking fine to me.
Also, I edited the app.use statements and added an extra one.
I think you have to parse request to JSON.
your code is:-
$.ajax({
method: "POST",
contentType: 'application/json',
dataType: 'json',
url: "localhost:8000/login",
//here you used JSON.stringify and on server side you have to parse it to use 'user' and 'pass' as a key of json
data: JSON.stringify({user:"john", pass:"123"}),
error: function () {
alert('error');
},
success: function (data) {
alert('success');
}
});
on the server side
<br>
app.post('/login', function (req, res) {
//parse data to JSON for further use
var dataObj = JSON.parse(req.body.data);
if(dataObj.user == 'john' && dataObj.password == '123') {
res.status(200);
} else {
res.status(401);
}
});

$.ajax is not a function when being called

for some reason when I run npm start and I hit the browser, I am getting this stack trace with this error.
TypeError: $.ajax is not a function
at getLocationFromIp (G:\Github\Expressjs\nodetest1\routes\index.js:13:7)
at G:\Github\Expressjs\nodetest1\routes\index.js:24:14
Would someone be able to tell me why? Here is my code. Thanks!
var express = require('express');
var router = express.Router();
var externalip = require('external-ip');
var $ = require('jquery');
getLocationFromIp = function() {
$.ajax({
url:"freegeoip.net/json/",
type: "GET",
data: null,
dataType: "json",
success: function(){console.log("success!")}
});
}
router.get('/', function(req, res) {
var ip = getLocationFromIp();
res.render('index', { 'ip' : "hi"});
});
See the documentation:
For jQuery to work in Node, a window with a document is required. Since no such window exists natively in Node, one can be mocked by tools such as jsdom. This can be useful for testing purposes.
var externalip = require('external-ip');
require("jsdom").env("", function(err, window) {
if (err) {
console.error(err);
return;
}
var $ = require("jquery")(window);
function getLocationFromIp() {
$.ajax({
url: "freegeoip.net/json/",
type: "GET",
data: null,
dataType: "json",
success: function() {
console.log("success!")
},
error: function() {
console.log("error", arguments[2])
}
});
}
var ip = getLocationFromIp();
console.log(ip);
});
You'd probably be better off using an HTTP library designed to work with Node from the outset, such such as request.
If you are using jquery to just make a http request, you can probably use the http or request node module to do that instead.
var express = require('express');
var router = express.Router();
var externalip = require('external-ip');
var http = require('http');
getLocationFromIp = function(done) {
var options = {
host: "freegeoip.net",
port: 80,
path: "/json"
};
var request = http.get(options, function(response) {
var result = "";
var responseCode = response.statusCode;
response.on('data', function(data) {
result += data;
});
response.on('end', function() {
if(responseCode >= 400)
return done(result, null);
else
return done(false, JSON.parse(result));
});
});
request.on("error", function(error){
return done("Error handling error", null);
});
request.end();
}
router.get('/', function(req, res) {
var ip = getLocationFromIp(function(error, ip){
res.render('index', { 'ip' : "hi"});
});
});

node js error on response methods between server and client

Hey im currently working on my first real webpage using node.js
Im using Express, ejs for layout and redis as database. Im trying to send an ajax call from my index page through my client to my server, use the ajax-call there and pass the final json back to my client where i try to render it on the next ejs page.
Ajax:
$(function(){
$(".search").click(function() {
$.ajax({
method: "POST",
url: "/search",
cache: false,
data: {ort: "hierundda", activity: "Wandern", datum: "01.09.2015"},
dataType: "json",
success: function(data){
alert('Success!')
}
, error: function(jqXHR, textStatus, err){
alert('text status '+textStatus+', err '+err)
}
});
});
});
My server route:
rest.post("/search", jsonParser, function(req, res){
/*some database action with redis */
res.json(dataJson);
});
});
My client route:
app.post('/search', jsonParser, function(req,res){
var test = JSON.stringify(req.body);
fs.readFile('./filterergebnis.ejs', {encoding: 'utf-8'}, function(err, filestring){
if(err){
throw err;
}
else{
var options = {
host: 'localhost',
port: 3000,
path: '/search',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': test.length
}
}
var req = http.request(options, function(res) {
res.on('data', function (chunk) {
var userdata = JSON.parse(chunk);
console.log(userdata);
var html = ejs.render(filestring, userdata);
//here does the error appear...
res.setHeader('content-type', 'text/html');
res.writeHead(200);
res.write(html);
res.end();
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.write(test);
req.end();
}
});
});
This is what the error looks like:
http://www.pic-upload.de/view-28225954/stack.png.html
index.ejs is running on default
You're using conflicting res variable names. Check the variable names of the callbacks from app.post() and http.request().
If you change to response instead, it might work, if there is no other problems:
var req = http.request(options, function(response) {
response.on('data', function (chunk) {
...

Categories